Skip to content

Instantly share code, notes, and snippets.

@ajozwik
Created January 21, 2015 18:12
Show Gist options
  • Save ajozwik/4ebd7add14e0f74369f9 to your computer and use it in GitHub Desktop.
Save ajozwik/4ebd7add14e0f74369f9 to your computer and use it in GitHub Desktop.
object P04 {
def groupIndexed[T](ts: Seq[(T, Int)]): Map[T, Seq[Int]] = {
val (toMap, max) = splitToMap(ts)
toMap.map {
case (t, seq) =>
val array = new Array[Int](max)
seq.foreach { i =>
array(i - 1) = 1
}
(t, array.toSeq)
}
}
private def splitToMap[T](ts: Seq[(T, Int)]) = ts.foldLeft((Map.empty[T, Seq[Int]], 1)) {
case ((map, max), (t, v)) =>
val a = map.getOrElse(t, Seq.empty[Int])
(map + (t -> (v +: a)), max.max(v))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment