Skip to content

Instantly share code, notes, and snippets.

@TJC
Created March 1, 2012 03:13
Show Gist options
  • Save TJC/1946959 to your computer and use it in GitHub Desktop.
Save TJC/1946959 to your computer and use it in GitHub Desktop.
Another attempt at Scala ranges challenge
// This method works, but I'm trying to shrink it in the form further down..
def ranges(ints: Seq[Int]): Seq[(Int, Int)] = {
ints.sorted.foldLeft( Seq[(Int,Int)]() )(
(acc: Seq[(Int,Int)], n: Int) => acc match {
case acc if (acc.nonEmpty) => acc.last match {
case (a,z) if (z == n) => acc
case (a,z) if (z+1 == n) => acc.init :+ (a, n)
case _ => acc :+ (n,n)
}
case _ => acc :+ (n,n)
}
)
}
// This method doesn't work, because I can't seem to match against the last element in a list..
def ranges(ints: Seq[Int]): Seq[(Int, Int)] = {
ints.sorted.foldLeft( Seq[(Int,Int)]() )(
(acc: Seq[(Int,Int)], n: Int) => acc match {
// case Nil => acc :+ (n,n)
case x :: (a,z) if (z == n) => acc
case x :: (a,z) if (z+1 == n) => x :+ (a, n)
case _ => acc :+ (n,n)
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment