View Problem

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
ExpandDiskEdit
ruby
common = [] ; [4, 5].each {|n| ['a', 'b', 'c'].each {|l| common << [l, n]}}
DiskEdit
csharp .NET 3.5
using System.Collections.Generic;
public class ListCombiner {
public static void Main() {
var letters = new List<char>() { 'a', 'b', 'c' };
var numbers = new List<int>() { 1, 2, 3 };

// result is a list that contaings lists of objects
var result = new List<List<object>>();
foreach (var l in letters) {
foreach (var n in numbers) {
result.Add(new List<object>() { l, n });
}
}
}
}
DiskEdit
clojure
(defn combine [lst1 lst2]
(mapcat (fn [x] (map #(list % x) lst1)) lst2))
DiskEdit
clojure
(mapcat (fn [x] (map #(list % x) ["a", "b", "c"])) [4, 5])
ExpandDiskEdit
fsharp
let combinations = (List.fold_left (fun acc number -> acc @ (List.map (fun letter -> (letter, number)) letters)) [] numbers)
ExpandDiskEdit
fsharp
let combinations aa bb =
aa
|> List.map (fun a -> bb |> List.map (fun b -> (a, b)))
|> List.concat
ExpandDiskEdit
groovy
letters = ['a', 'b', 'c']
numbers = [4, 5]
combos = [letters, numbers].combinations()
DiskEdit
haskell
comb :: [(String, Int)]
comb = do
b <- [4,5]
a <- ["a","b","c"]
return (a,b)

main = mapM_ print comb
DiskEdit
haskell
comb :: [(String, Int)]
comb = [(a, b) | b <- [4,5], a <- ["a","b","c"]]

main = print comb

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