View Problem
Categorise a list
Given the list
Submit a new solution for ruby, cpp, fsharp, erlang ...
There are 14 other solutions in additional languages (clojure, fantom, groovy, java ...)
[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
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
}
}
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
}
}
haskell
import Data.List (groupBy, sortBy)
import Data.Function (on)
groupInPairsBy :: Ord k => (a -> k) -> [a] -> [(k, [a])]
groupInPairsBy f = map (\xs -> (f (head xs), xs)) .
groupBy ((==) `on` f) . sortBy (compare `on` f)
output :: [(Int, [String])]
output = groupInPairsBy length ["one", "two", "three", "four", "five"]
import Data.Function (on)
groupInPairsBy :: Ord k => (a -> k) -> [a] -> [(k, [a])]
groupInPairsBy f = map (\xs -> (f (head xs), xs)) .
groupBy ((==) `on` f) . sortBy (compare `on` f)
output :: [(Int, [String])]
output = groupInPairsBy length ["one", "two", "three", "four", "five"]
Submit a new solution for ruby, cpp, fsharp, erlang ...
There are 14 other solutions in additional languages (clojure, fantom, groovy, java ...)




