Skip to content

Instantly share code, notes, and snippets.

@TheDIM47
Created February 3, 2021 11:24
Show Gist options
  • Save TheDIM47/7f16045a092405b97123e362b14950c3 to your computer and use it in GitHub Desktop.
Save TheDIM47/7f16045a092405b97123e362b14950c3 to your computer and use it in GitHub Desktop.
/**
* Join list of lists by order of elements
* val a = List(3, 5, 6)
* val b = List(1, 2, 7, 8)
* val expected = List(3, 1, 2, 5, 6, 7, 8)
*
* @param lists list of lists of elements
* @return list of elements
*/
def join[A](lists: List[List[A]]): List[A] = {
@annotation.tailrec
def go[A](ls: List[List[A]], rem: List[List[A]], res: List[A]): List[A] =
ls match {
case x :: xs =>
go(
xs,
if (x.isEmpty) rem else (x.tail :: rem),
if (x.isEmpty) res else x.head :: res
)
case Nil if rem.nonEmpty =>
go(rem, Nil, res)
case Nil => res
}
go(lists, Nil, Nil).reverse
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment