Created
March 1, 2012 03:13
-
-
Save TJC/1946959 to your computer and use it in GitHub Desktop.
Another attempt at Scala ranges challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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