2

Given:

scala> val a = (1 to 8).toList.grouped(3).toList
a: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8))

How to reverse dimension and group elements in a in this way:

List(List(1, 4, 7), List(2, 5, 8), List(3, 6))
ekad
  • 14,436
  • 26
  • 44
  • 46
StopKran
  • 395
  • 5
  • 22

3 Answers3

2

You can try this method, find out the length of the longest List and then collect elements from each sub list while looping through the indices:

val maxLength = a.map(_.length).max
// maxLength: Int = 3

(0 until maxLength) map (i => a flatMap (List(i) collect _))
// res45: scala.collection.immutable.IndexedSeq[List[Int]] = 
//        Vector(List(1, 4, 7), List(2, 5, 8), List(3, 6))
Psidom
  • 209,562
  • 33
  • 339
  • 356
2

Maybe you want transpose method, but official transpoes method doesn't support unequal length of sublist. maybe you want to try:

Is there a safe way in Scala to transpose a List of unequal-length Lists?

Community
  • 1
  • 1
chengpohi
  • 14,064
  • 1
  • 24
  • 42
2

Should use the groupBy method to group elements in the list. In your example, you are grouping every third element. In my solution, I am using the modulus operator to group every third element in the list:

val a = (1 to 8).toList.groupBy(_ % 3).values.toList
a: List[List[Int]] = List(List(2, 5, 8), List(1, 4, 7), List(3, 6))

If you want the results sorted (as in your example) then add the sortBy() at the end:

val a = (1 to 8).toList.groupBy(_ % 3).values.toList.sortBy(_(0))
a: List[List[Int]] = List(List(1, 4, 7), List(2, 5, 8), List(3, 6))
SanyTech
  • 56
  • 4