Skip to content

Instantly share code, notes, and snippets.

@ajozwik
Last active August 29, 2015 14:13
Show Gist options
  • Save ajozwik/f8ee308c68f531cc62c9 to your computer and use it in GitHub Desktop.
Save ajozwik/f8ee308c68f531cc62c9 to your computer and use it in GitHub Desktop.
object P04 {
def groupIndexed[T](ts: Seq[(T, Int)]): Map[T, Seq[Int]] = {
val (toMap, size) = convertToMapAndSize(ts)
toMap.map {
case (t, seq) =>
val range = (1 to size).map(i => if (seq.contains(i)) 1 else 0)
(t, range)
}
}
private def convertToMapAndSize[T](ts: Seq[(T, Int)]) = ts.foldLeft((Map.empty[T, Set[Int]], 1)) {
case ((map, max), (t, v)) =>
val a = map.getOrElse(t, Set.empty[Int])
(map + (t -> (a + v)), max.max(v))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment