Jump to content

Cartesian product of two or more lists: Difference between revisions

Add APL
(Adding a new method based on recursion)
(Add APL)
Line 46:
[]
[]
</pre>
 
=={{header|APL}}==
 
APL has a built-in outer product operator: <code>X ∘.F Y</code> will get you an ⍴X-by-⍴Y
matrix containing every corresponding value of <code>x F y</code> for all x∊X, y∊Y.
 
The Cartesian product can therefore be expressed as <code>∘.,</code>, but as that would return
a matrix, and the task is asking for a list, you also need to ravel the result.
 
<lang APL>cart ← ,∘.,</lang>
 
{{out}}
 
<pre> 1 2 cart 3 4
1 3 1 4 2 3 2 4
3 4 cart 1 2
3 1 3 2 4 1 4 2
1 2 cart ⍬ ⍝ empty output
 
⍬ cart 1 2 ⍝ empty output again
 
</pre>
 
This can be reduced over a list of lists to generate the Cartesian product of an arbitrary
list of lists.
 
<lang APL>nary_cart ← ⊃(,∘.,)/</lang>
 
{{out}}
 
The items are listed on separate lines (using ↑) for clarity.
 
<pre style="height: 50ex">
↑nary_cart (1776 1789)(7 12)(4 14 23)(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
↑nary_cart(1 2 3)(,30)(50 100)
1 30 50
1 30 100
2 30 50
2 30 100
3 30 50
3 30 100
↑nary_cart(1 2 3)(⍬)(50 100) ⍝ empty output
</pre>
 
2,115

edits

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