Anonymous user
Cartesian product of two or more lists: Difference between revisions
→{{header|Groovy}}: Changed to a "more natural" multiply operator overload
(→{{header|Groovy}}: Initial solution) |
(→{{header|Groovy}}: Changed to a "more natural" multiply operator overload) |
||
Line 844:
=={{header|Groovy}}==
'''Solution:'''<br>
The following ''CartesianCategory'' class allows for modification of regular ''Iterable'' interface behavior, overloading ''Iterable'''s ''multiply'' (*) operator to perform a Cartesian Product when the second operand is also an ''Iterable''.
<lang groovy>class CartesianCategory {
static Iterable multiply(Iterable a, Iterable b) {
assert
def
(0..<(
▲ (0..<(n0*n1)).inject([]) { prod, i -> prod << [lists[0][i.intdiv(n1)],lists[1][i%n1]] }
}
}</lang>
'''Test:'''<br>
The ''mixin'' method call is necessary to make the multiply (*) operator work.
<lang groovy>println "[1, 2] × [3, 4] = ${cartProd([1, 2], [3, 4])}"▼
<lang groovy>Iterable.metaClass.mixin CartesianCategory
println "[3, 4] × [1, 2] = ${cartProd([3, 4], [1, 2])}"▼
println "[1, 2] × [
println "[
println "[1, 2
println "[
println "[1776, 1789] × [7, 12] × [4, 14, 23] × [0, 1] = ${[1776, 1789] * [7, 12] * [4, 14, 23] * [0, 1]}"
println "[John,Paul,George,Ringo] × [Emerson,Lake,Palmer] × [Simon,Garfunkle] = ["
println "]"</lang>
'''Output:'''
|