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])).
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
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

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