mop mop - 9 months ago 37
Scala Question

how to sort multiple colmuns (more than ten columns) in scala language?

how to sort multiple colmuns (more than ten columns) in scala language.
for example:

1 2 3 4
4 5 6 3
1 2 1 1
‌2 3 5 10

=>

1 2 1 1
1 2 3 3
2 3 5 4
4 5 6 10

Answer Source

Not much to it.

val input = io.Source.fromFile("junk.txt")   // open file
                     .getLines               // load all contents
                     .map(_.split("\\W+"))   // turn rows into Arrays
                     .map(_.map(_.toInt))    // Arrays of Ints

val output = input.toList          // from Iterator to List
                  .transpose       // swap rows/columns
                  .map(_.sorted)   // sort rows
                  .transpose       // swap back

output.foreach(x => println(x.mkString(" ")))  // report results

Note: This allows any whitespace between the numbers but it will fail to create the expected Array[Int] if it encounters other separators (commas, etc.) or if the line begins with a space.

Also, transpose will throw if the rows aren't all the same size.