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:
1 | 2 | 3 |
4 | 5 | 6 |
Becomes:
1 | 2 |
3 | 4 |
5 | 6 |
Test cases in Scala
This algorithm comes with test cases.
To see the free test cases for all our algos, as well as run them in our TDD IDE, Register (free).
Algorithm in Scala
4 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
Get the full algorithm !
or
'Unlimited Scala Algorithms' gives you access to all the 94 published & 6 upcoming Scala Algorithms (100 total)!
Upon purchase, you will be able to Register an account to access all the algorithms on multiple devices.
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
View
The
.view
syntax creates a structure that mirrors another structure, until "forced" by an eager operation like .toList, .foreach, .forall, .count.