StopKran
StopKran

Reputation: 395

In Scala how to group elements in list with reverse dimension?

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))

Upvotes: 2

Views: 465

Answers (3)

SanyTech
SanyTech

Reputation: 56

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))

Upvotes: 2

chengpohi
chengpohi

Reputation: 14227

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?

Upvotes: 2

akuiper
akuiper

Reputation: 215047

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))

Upvotes: 2

Related Questions