View Problem

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
ExpandDiskEdit
ruby
lengths = {}
list.each do |x|
len = x.size
lengths[len] = (lengths[len] || [])
lengths[len] << x
end
ExpandDiskEdit
ruby 1.8.7+
lengths = list.group_by {|x| x.size}
DiskEdit
ruby ruby 1.8+
list.inject({}) { |h,x| (h[x.size]||=[]) << x; h }
ExpandDiskEdit
cpp C++/CLI .NET 2.0
for each(String^ entry in input)
{
key = entry->Length;
if (!hash->ContainsKey(key)) hash[key] = gcnew ArrayList;
safe_cast<ArrayList^>(hash[key])->Add(entry);
}
ExpandDiskEdit
fsharp
let catmap = (List.foldLeft (fun (acc : Map<int, List<string> >) (e : string) -> if (Map.mem e.Length acc) then (Map.add e.Length ((Map.find e.Length acc) @ [e]) acc) ; else (Map.add e.Length [e] acc)) (Map.empty) list)
DiskEdit
fsharp
let lengthMap =
["one"; "two"; "three"; "four"; "five"]
|> Seq.groupBy (fun s -> s.Length)
|> Seq.map (fun (length, entries) -> (length, entries |> List.ofSeq))
|> Map.ofSeq
DiskEdit
clojure
(loop [m {}
l ["one" "two" "three" "four" "five"]]
(if (zero? (count l))
m
(let [item (first l)
key (count item)]
(recur
(assoc m key (cons item (get m key [])))
(rest l)))))
DiskEdit
clojure
(group-by count ["one" "two" "three" "four" "five"])

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