Scala algorithm: Reshape a matrix

Published

Algorithm goal

Turn an m-by-n matrix into an n-by-m matrix, retaining the order of the elements. For example:

123
456

Becomes:

12
34
56

Test cases in Scala

assert(reshapeMatrix(Vector.empty) == Vector.empty)
assert(reshapeMatrix(Vector(Vector(1))) == Vector(Vector(1)))
assert(reshapeMatrix(Vector(Vector(1, 2))) == Vector(Vector(1), Vector(2)))
assert(
  reshapeMatrix(Vector(Vector(1, 2), Vector(3, 4))) ==
    Vector(Vector(1, 2), Vector(3, 4))
)
assert(
  reshapeMatrix(Vector(Vector(1, 2, 3), Vector(4, 5, 6))) ==
    Vector(Vector(1, 2), Vector(3, 4), Vector(5, 6))
)

Algorithm in Scala

3 lines of Scala (version 2.13), showing how concise Scala can be!

Get the full algorithm Scala algorithms logo, maze part, which looks quirky!

or

'Unlimited Scala Algorithms' gives you access to all the Scala Algorithms!

Upon purchase, you will be able to Register an account to access all the algorithms on multiple devices.

Stripe logo

Explanation

In Scala this is straightforward: flatten the whole matrix, and then group the elements into chunks of length of the height of the matrix (.grouped). (this is © from www.scala-algorithms.com)

Scala concepts & Hints

  1. View

    The .view syntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.

View the rest of Scala algorithms