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
perl
foreach(@list) {
$histogram{$_}++;
}
DiskEdit
perl
$histogram{$_}++ for @list;
ExpandDiskEdit
java
Map map = new HashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
String s = (String) it.next();
if (!map.containsKey(s)) {
map.put(s, new Integer(1));
} else {
map.put(s, new Integer(((Integer)map.get(s)).intValue() + 1));
}
}
ExpandDiskEdit
java org.apache.commons
LinkedMap histogram = new LinkedMap();

for (Object letter : list)
histogram.put(letter, !histogram.containsKey(letter) ? 1 : MapUtils.getIntValue(histogram, letter) + 1);
DiskEdit
clojure
(let [l '[a b a c b b]]
(loop [m {}
d (distinct l)]
(let [item (first d)]
(if (zero? (count d))
m
(recur
(assoc m
item
(count
(filter #(= item %) l)))
(rest d))))))
DiskEdit
clojure
(->> [:a :b :a :c :b :b]
(group-by identity)
(reduce (fn [m e] (assoc m (first e) (count (second e)))) {}))
DiskEdit
clojure
(reduce conj {} (for [[x xs] (group-by identity "abacbb")] [x (count xs)]))
DiskEdit
clojure
(frequencies ["a","b","a","c","b","b"])
DiskEdit
clojure
(frequencies '[a b a c b b])
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])).

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