Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two collections by interleaving values

How can I merge two lists / Seqs so it takes 1 element from list 1, then 1 element from list 2, and so on, instead of just appending list 2 at the end of list 1?

E.g [1,2] + [3,4] = [1,3,2,4]

and not [1,2,3,4]

Any ideas? Most concat methods I've looked at seem to do to the latter and not the former.

like image 477
Ali Avatar asked Aug 01 '19 15:08

Ali


3 Answers

Another way:

List(List(1,2), List(3,4)).transpose.flatten
like image 181
Krzysztof Atłasik Avatar answered Oct 28 '22 08:10

Krzysztof Atłasik


So maybe your collections aren't always the same size. Using zip in that situation would create data loss.

def interleave[A](a :Seq[A], b :Seq[A]) :Seq[A] =
  if (a.isEmpty) b else if (b.isEmpty) a
  else a.head +: b.head +: interleave(a.tail, b.tail)

interleave(List(1, 2, 17, 27)
          ,Vector(3, 4))  //res0: Seq[Int] = List(1, 3, 2, 4, 17, 27)
like image 6
jwvh Avatar answered Oct 28 '22 10:10

jwvh


You can do:

val l1 = List(1, 2)
val l2 = List(3, 4)
l1.zip(l2).flatMap { case (a, b) => List(a, b) }
like image 5
Jean Logeart Avatar answered Oct 28 '22 09:10

Jean Logeart