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
ruby
histogram = {}
list.each { |item| histogram[item] = (histogram[item] || 0) +1 }
DiskEdit
ruby 1.9
list = %w{a b a c b b}

histogram = list.each_with_object(Hash.new(0)) do |item, hash|
hash[item] += 1
end

p histogram # => {"a"=>2, "b"=>3, "c"=>1}
DiskEdit
ruby
list.inject(Hash.new(0)) {|h, item| h[item] += 1; h}
ExpandDiskEdit
erlang
% Imperative Solution
Histogram = histogram(List),
ExpandDiskEdit
erlang
% Functional (1) Solution
Histogram = histogram(List),
DiskEdit
erlang Using dict for a map.
lists:foldl(fun(Elem, OldDict) ->
dict:update_counter(Elem, 1, OldDict)
end,
dict:new(),
[a,b,a,c,b,b])).
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;
ExpandDiskEdit
fantom
list := ["a","b","a","c","b","b"]
map := [Str:Int][:]
list.each |Str s, Int i| { if(!map.containsKey(s)) map.add(s,1); else map[s] = ++map[s] }
echo (map)

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