View Problem

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
ExpandDiskEdit
scala
list foreach { (x) => histogram += x -> (histogram.getOrElse(x, 0) + 1) }
ExpandDiskEdit
scala
val data = List("a", "b", "a", "c", "b", "b")
val keys = data removeDuplicates
val hist = Map.empty[String, Int] ++ keys.map{ k => (k, (data count (_==k)))}
assert(hist == Map("a"->2, "b"->3, "c"->1))
ExpandDiskEdit
scala
val histEntries = for {
key <- data.removeDuplicates
count = data.count(_ == key)
} yield (key -> count)
val hist = Map(histEntries: _*)
DiskEdit
scala
value.foldLeft(Map[T, Int]()){
(m, c) => m.updated(c, m.getOrElse(c, 0) + 1)
}
ExpandDiskEdit
scala scala

list.groupBy(identity).mapValues(_.size)

Submit a new solution for scala
There are 37 other solutions in additional languages (clojure, cpp, csharp, erlang ...)