How to transpose a matrix (swap rows and columns) in Scala

3 Answers

0 votes
object Main {
  def main(args: Array[String]): Unit = {
    val matrix = List(
      List(1, 2, 3),
      List(4, 5, 6),
      List(7, 8, 9)
    )

    val t = matrix.transpose

    t.foreach(row => println(row.mkString(" ")))
  }
}



/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 23 hours ago by avibootz
0 votes
object Main {
  def transpose[A](matrix: List[List[A]]): List[List[A]] = {
    val rows = matrix.length
    val cols = matrix.head.length

    (0 until cols).map { j =>
      (0 until rows).map { i =>
        matrix(i)(j)
      }.toList
    }.toList
  }

  def main(args: Array[String]): Unit = {
    val matrix = List(
      List(1, 2, 3),
      List(4, 5, 6),
      List(7, 8, 9)
    )

    val t = transpose(matrix)
    t.foreach(row => println(row.mkString(" ")))
  }
}



/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 23 hours ago by avibootz
0 votes
object Main {
  // Functional Scala
  def transpose[A](matrix: List[List[A]]): List[List[A]] =
    matrix.head.indices.map(i => matrix.map(_(i))).toList

  def main(args: Array[String]): Unit = {
    val matrix = List(
      List(1, 2, 3),
      List(4, 5, 6),
      List(7, 8, 9)
    )

    val t = transpose(matrix)
    t.foreach(row => println(row.mkString(" ")))
  }
}



/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 23 hours ago by avibootz
...