Jump to content

Cartesian product of two or more lists: Difference between revisions

Added Wren
m (\ replaced with lambdas)
(Added Wren)
Line 3,977:
{(1, 30, 500), (1, 30, 100), (2, 30, 500), (2, 30, 100), (3, 30, 500), (3, 30, 100)}
{}</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-seq}}
<lang ecmascript>import "/seq" for Lst
 
var prod2 = Fn.new { |l1, l2|
var res = []
for (e1 in l1) {
for (e2 in l2) res.add([e1, e2])
}
return res
}
 
var prodN = Fn.new { |ll|
if (ll.count < 2) Fiber.abort("There must be at least two lists.")
var p2 = prod2.call(ll[0], ll[1])
return ll.skip(2).reduce(p2) { |acc, l| prod2.call(acc, l) }.map { |l| Lst.flatten(l) }.toList
}
 
var printProdN = Fn.new { |ll|
System.print("%(ll.join(" x ")) = ")
System.write("[\n ")
System.print(prodN.call(ll).join("\n "))
System.print("]\n")
}
 
System.print("[1, 2] x [3, 4] = %(prodN.call([ [1, 2], [3, 4] ]))")
System.print("[3, 4] x [1, 2] = %(prodN.call([ [3, 4], [1, 2] ]))")
System.print("[1, 2] x [] = %(prodN.call([ [1, 2], [] ]))")
System.print("[] x [1, 2] = %(prodN.call([ [], [1, 2] ]))")
System.print("[1, a] x [2, b] = %(prodN.call([ [1, "a"], [2, "b"] ]))")
System.print()
printProdN.call([ [1776, 1789], [7, 12], [4, 14, 23], [0, 1] ])
printProdN.call([ [1, 2, 3], [30], [500, 100] ])
printProdN.call([ [1, 2, 3], [], [500, 100] ])
printProdN.call([ [1, 2, 3], [30], ["a", "b"] ])</lang>
 
{{out}}
<pre>
[1, 2] x [3, 4] = [[1, 3], [1, 4], [2, 3], [2, 4]]
[3, 4] x [1, 2] = [[3, 1], [3, 2], [4, 1], [4, 2]]
[1, 2] x [] = []
[] x [1, 2] = []
[1, a] x [2, b] = [[1, 2], [1, b], [a, 2], [a, b]]
 
[1776, 1789] x [7, 12] x [4, 14, 23] x [0, 1] =
[
[1776, 7, 4, 0]
[1776, 7, 4, 1]
[1776, 7, 14, 0]
[1776, 7, 14, 1]
[1776, 7, 23, 0]
[1776, 7, 23, 1]
[1776, 12, 4, 0]
[1776, 12, 4, 1]
[1776, 12, 14, 0]
[1776, 12, 14, 1]
[1776, 12, 23, 0]
[1776, 12, 23, 1]
[1789, 7, 4, 0]
[1789, 7, 4, 1]
[1789, 7, 14, 0]
[1789, 7, 14, 1]
[1789, 7, 23, 0]
[1789, 7, 23, 1]
[1789, 12, 4, 0]
[1789, 12, 4, 1]
[1789, 12, 14, 0]
[1789, 12, 14, 1]
[1789, 12, 23, 0]
[1789, 12, 23, 1]
]
 
[1, 2, 3] x [30] x [500, 100] =
[
[1, 30, 500]
[1, 30, 100]
[2, 30, 500]
[2, 30, 100]
[3, 30, 500]
[3, 30, 100]
]
 
[1, 2, 3] x [] x [500, 100] =
[
]
 
[1, 2, 3] x [30] x [a, b] =
[
[1, 30, a]
[1, 30, b]
[2, 30, a]
[2, 30, b]
[3, 30, a]
[3, 30, b]
]
</pre>
 
=={{header|zkl}}==
9,486

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.