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
DiskEdit
python
from collections import defaultdict
h = defaultdict(int)
for k in "abacbb":
h[k] += 1

h = {}
for k in "abacbb":
h[k] = h.setdefault(k, 0) + 1
DiskEdit
python 2.7+, 3.1+
from collections import Counter
h = Counter("abacbb")
print(h)
ExpandDiskEdit
fsharp
let histogram = (List.foldLeft (fun (acc : Map<char, int>) (e : char) -> if (Map.mem e acc) then (Map.add e ((Map.find e acc) + 1) acc) ; else (Map.add e 1 acc)) (Map.empty) list)
ExpandDiskEdit
fsharp
let histogram list =
let rec histogram' list' dict' =
match list' with
| [] -> dict'
| x :: xs ->
match Map.tryFind x dict' with
| Some(Value) -> histogram' xs (Map.add x (Value + 1) dict')
| None -> histogram' xs (Map.add x 1 dict')
histogram' list Map.empty

// ------

let histogram' = histogram list
ExpandDiskEdit
fsharp
let histogram = (List.foldLeft (fun (acc : Generic.Dictionary<char, int>) (e : char) -> (if acc.ContainsKey(e) then acc.[e] <- acc.[e] + 1 ; else acc.Add(e, 1)) ; acc) (new Generic.Dictionary<char, int>()) list)
ExpandDiskEdit
fsharp 2.0
let histogram =
list
|> Seq.groupBy (fun a -> a)
|> Seq.map(fun (key, elements) -> key, Seq.length elements)
|> Map.ofSeq
ExpandDiskEdit
cpp C++/CLI .NET 2.0
for each(String^ entry in input) hash[entry] = hash->ContainsKey(entry)
? Convert::ToInt32(hash[entry]->ToString()) + 1 : 1;
ExpandDiskEdit
cpp C++/CLI .NET 2.0
for each(String^ entry in input) dict[entry] = dict->ContainsKey(entry) ? dict[entry] + 1 : 1;
ExpandDiskEdit
cpp C++0x/C++11
map<string,int> hist;
for (auto e: { "a","b","a","c","b","b" })
++hist[e];
for (auto e: hist)
cout << e.first << " : " << e.second << endl;

Submit a new solution for python, fsharp, or cpp
There are 30 other solutions in additional languages (clojure, csharp, erlang, fantom ...)