Jump to content

Cartesian product of two or more lists: Difference between revisions

Added Crystal implementation
(Added Crystal implementation)
Line 781:
NIL
</lang>
 
=={{header|Crystal}}==
The first function is the basic task. The version overloaded for one argument is the extra credit task, implemented using recursion.
<lang crystal>def cartesian_product(a, b)
return a.flat_map { |i| b.map { |j| [i, j] } }
end
 
 
def cartesian_product(l)
if l.size <= 1
return l
elsif l.size == 2
return cartesian_product(l[0], l[1])
end
 
return l[0].flat_map { |i|
cartesian_product(l[1..]).map { |j|
[i, j].flatten
}
}
end
 
 
tests = [ [[1, 2], [3, 4]],
[[3, 4], [1, 2]],
[[1, 2], [] of Int32],
[[] of Int32, [1, 2]],
[[1, 2, 3], [30], [500, 100]],
[[1, 2, 3], [] of Int32, [500, 100]],
[[1776, 1789], [7, 12], [4, 14, 23], [0, 1]] ]
 
tests.each { |test|
puts "#{test.join(" x ")} ->"
puts " #{cartesian_product(test)}"
puts ""
}
</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, 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] ->
[]
 
[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]]
</pre>
 
=={{header|D}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.