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
java
SortedMap<Integer, List<String> > map = new TreeMap<Integer, List<String> >(); int key; List<String> vlist;

for (String item : list)
{
key = item.length(); vlist = map.containsKey(key) ? map.get(key) : new ArrayList<String>();
vlist.add(item); map.put(key, vlist);
}
ExpandDiskEdit
java org.apache.commons
MultiValueMap map = new MultiValueMap();
for (Object item : list) map.put(((String) item).length(), item);
DiskEdit
perl
@list = qw(one two three four five);
push @{$map{length($_)}}, $_ for (@list);
ExpandDiskEdit
groovy
map = ['one', 'two', 'three', 'four', 'five'].groupBy{ it.size() }
ExpandDiskEdit
scala
list foreach { (x) => map += x.length -> (x :: map.getOrElse(x.length, Nil)) }
ExpandDiskEdit
scala
list foreach { (x) => map += x.length -> (map.getOrElse(x.length, Nil) ::: List(x)) }
ExpandDiskEdit
scala
List("one", "two", "three", "four", "five") groupBy (_ size)
DiskEdit
python
c = defaultdict(list)
for k in ["one", "two", "four", "three", "five"]:
c[len(k)].append(k)
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.fold_left (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)
ExpandDiskEdit
erlang
% Imperative Solution
CatList = categorise(List),
ExpandDiskEdit
erlang
% Functional (1) Solution
CatList = categorise(List),
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
php
foreach ($array as $m) {
$l = strlen($m);
$map[$l][] = $m;
}
arsort($map);

Submit a new solution for ruby, java, perl, groovy ...