Skip to content

Instantly share code, notes, and snippets.

@machisuji
Created February 25, 2010 22:03
Show Gist options
  • Save machisuji/315088 to your computer and use it in GitHub Desktop.
Save machisuji/315088 to your computer and use it in GitHub Desktop.
Splitting a list into two lists containing alternating elements of the original list.
// way faster than split2m
def split2f[T](list: Seq[T]): (Seq[T], Seq[T]) = {
val it = Iterator.iterate(true)(!_)
list.partition(_ => it.next)
}
// next approach, incredibly slow
// @TODO learn functional programming
def split2m[T](list: Seq[T]): (Seq[T], Seq[T]) =
list.foldLeft((Seq[T](), Seq[T]())) {
(tuple: (Seq[T], Seq[T]), element: T) =>
if (tuple._1.size <= tuple._2.size) (tuple._1 :+ element, tuple._2)
else (tuple._1, tuple._2 :+ element)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment