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 }
DiskEdit
csharp .NET 3.5
using System.Collections.Generic;
using System.Linq;
public class ListCategorizer {
public static void Main() {
var list = new List<string>() { "one", "two", "three", "four", "five" };
var categories = list.GroupBy(el => el.Length)
.ToDictionary( g => g.Key, // key
g => g.ToList() ); // value
}
}
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
fantom
list := ["one", "two", "three", "four", "five"]
map := [Int:List][:]
list.each { List l := map[it.size] ?: [,]; map[it.size] = l.add(it) }
echo(map)
ExpandDiskEdit
erlang
% Imperative Solution
CatList = categorise(List),
ExpandDiskEdit
erlang
% Functional (1) Solution
CatList = categorise(List),

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