Cartesian product of two or more lists: Difference between revisions
Cartesian product of two or more lists (view source)
Revision as of 19:05, 26 August 2022
, 1 year agosyntax highlighting fixup automation
Alpha bravo (talk | contribs) (Added AutoHotkey) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 24:
=={{header|11l}}==
{{trans|Go}}
<
V p = [(0, 0)] * (a.len * b.len)
V i = 0
Line 36:
[Int] empty_array
print(cart_prod([1, 2], empty_array))
print(cart_prod(empty_array, [1, 2]))</
====Alternative version====
<
R multiloop(a, b, (aa, bb) -> (aa, bb))</
{{out}}
<pre>
Line 49:
=={{header|Action!}}==
<
DEFINE MAX_RESULT="100"
Line 158:
a(0)=a8 a(1)=a9 a(2)=a10 Test(a,3) PutE()
a(0)=a8 a(1)=a3 a(2)=a10 Test(a,3)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Cartesian_product_of_two_or_more_lists.png Screenshot from Atari 8-bit computer]
Line 172:
=={{header|Ada}}==
<
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Strings.Fixed;
Line 275:
Put (List_1_2_3 * List_Empty * List'(Nil & 500 & 100)); New_Line;
end Cartesian;</
{{out}}
<pre>{(1,3),(1,4),(2,3),(2,4)}
Line 293:
a matrix, and the task is asking for a list, you also need to ravel the result.
<syntaxhighlight lang
{{out}}
Line 310:
list of lists.
<
{{out}}
Line 353:
=={{header|AppleScript}}==
<
-- Two lists:
Line 512:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</
{{Out}}
<pre>[[1, 3], [1, 4], [2, 3], [2, 4]]
Line 550:
=={{header|Arturo}}==
{{trans|Ruby}}
<
[[1 2][3 4]]
[[3 4][1 2]]
Line 560:
] 'lst [
print as.code product.cartesian lst
]</
{{out}}
Line 573:
=={{header|AutoHotkey}}==
<
(join,
[[1, 2], [3, 4]]
Line 626:
oTemp.Push(v)
Product.push(oTemp)
}</
{{out}}
<pre>[[1, 3], [1, 4], [2, 3], [2, 4]]
Line 636:
[]</pre>
=={{header|Bracmat}}==
<
= R a b A B
. :?R
Line 670:
& out$(cartprod$((.1 2 3) (.30) (.500 100)))
& out$(cartprod$((.1 2 3) (.) (.500 100)))
)</
<pre>. (.1776 7 4 0)
(.1776 7 4 1)
Line 706:
=={{header|C}}==
Recursive implementation for computing the Cartesian product of lists. In the pursuit of making it as interactive as possible, the parsing function ended up taking the most space. The product set expression must be supplied enclosed by double quotes. Prints out usage on incorrect invocation.
<syntaxhighlight lang=C>
#include<string.h>
#include<stdlib.h>
Line 823:
return 0;
}
</syntaxhighlight>
Invocation and output :
<pre>
Line 850:
=={{header|C sharp|C#}}==
<
public class Program
{
Line 893:
select acc.Concat(new [] { item }));
}
}</
{{out}}
<pre>
Line 904:
{}</pre>
If the number of lists is known, LINQ provides an easier solution:
<
{
///...
Line 919:
select (a, b, c);
Console.WriteLine($"{{{string.Join(", ", cart2)}}}");
}</
{{out}}
<pre>
Line 927:
=={{header|C++}}==
<
#include <iostream>
#include <vector>
Line 983:
std::cin.get();
return 0;
}</
{{out}}
Line 995:
=={{header|Clojure}}==
<
(ns clojure.examples.product
(:gen-class)
Line 1,007:
x (first colls)]
(cons x more))))
</syntaxhighlight>
'''Output'''
<
(doseq [lst [ [[1,2],[3,4]],
[[3,4],[1,2]], [[], [1, 2]],
Line 1,020:
(println lst "=>")
(pp/pprint (cart lst)))
</syntaxhighlight>
<pre>
Line 1,063:
=={{header|Common Lisp}}==
<
"Compute the cartesian product of two sets represented as lists"
(loop for x in s1
nconc (loop for y in s2 collect (list x y))))
</syntaxhighlight>
'''Output'''
<
CL-USER> (cartesian-product '(1 2) '(3 4))
((1 3) (1 4) (2 3) (2 4))
Line 1,080:
CL-USER> (cartesian-product '() '(1 2))
NIL
</syntaxhighlight>
'''Extra credit:'''
<
"Compute the n-cartesian product of a list of sets (each of them represented as list).
Algorithm:
Line 1,094:
(loop for x in (car l)
nconc (loop for y in (n-cartesian-product (cdr l))
collect (cons x y)))))</
'''Output:'''
<
((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))
CL-USER> (n-cartesian-product '((1 2 3) (30) (500 100)))
Line 1,104:
CL-USER> (n-cartesian-product '((1 2 3) () (500 100)))
NIL
</syntaxhighlight>
=={{header|Crystal}}==
The first function is the basic task. The version overloaded for one argument is the extra credit task, implemented using recursion.
<
return a.flat_map { |i| b.map { |j| [i, j] } }
end
Line 1,141:
puts ""
}
</syntaxhighlight>
{{out}}
Line 1,167:
=={{header|D}}==
<
void main() {
Line 1,205:
return Result();
}</
{{out}}
Line 1,215:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<
program Cartesian_product_of_two_or_more_lists;
Line 1,324:
{$IFNDEF UNIX} readln; {$ENDIF}
end.</
{{out}}
<pre>[[1 3] [1 4] [2 3] [2 4]]
Line 1,365:
=={{header|F Sharp|F#}}==
===The Task===
<
//Nigel Galloway February 12th., 2018
let cP2 n g = List.map (fun (n,g)->[n;g]) (List.allPairs n g)
</syntaxhighlight>
{{out}}
<pre>
Line 1,378:
===Extra Credit===
<
//Nigel Galloway August 14th., 2018
let cP ng=Seq.foldBack(fun n g->[for n' in n do for g' in g do yield n'::g']) ng [[]]
</syntaxhighlight>
{{out}}
<pre>
Line 1,399:
=={{header|Factor}}==
<
{ { { 1 3 } { 1 4 } } { { 2 3 } { 2 4 } } }
IN: scratchpad { 3 4 } { 1 2 } cartesian-product .
Line 1,406:
{ { } { } }
IN: scratchpad { } { 1 2 } cartesian-product .
{ }</
=={{header|FreeBASIC}}==
I'll leave the extra credit part for someone else. It's just going to amount to repeatedly finding Cartesian products and [[Flatten a list|flattening]] the result, so considerably less interesting than Cartesian products where the list items themselves can be lists.
<
type listitem ' An item of a list may be a number
Line 1,472:
R = cartprod(B, A) : print_list(R) : print
R = cartprod(A, EMPTY) : print_list(R) : print
R = cartprod(EMPTY, A) : print_list(R) : print</
{{out}}<pre>{{1, 3}, {1, 4}, {2, 3}, {2, 4}}
{{3, 1}, {3, 2}, {4, 1}, {4, 2}}
Line 1,482:
This implementation is hard to extend to n-ary products but it is simple and works well for binary products of lists of any length.
<
! Created by simon on 29/04/2021.
Line 1,581:
end subroutine print_product
end program cartesian_product
</syntaxhighlight>
'''Output:'''
{1,2} x {3,4} = {{1,3},{1,4},{2,3},{2,4}}
Line 1,600:
=={{header|Go}}==
'''Basic Task'''
<
import "fmt"
Line 1,623:
fmt.Println(cart2([]int{1, 2}, nil))
fmt.Println(cart2(nil, []int{1, 2}))
}</
{{out}}
<pre>
Line 1,634:
This solution minimizes allocations and computes and fills the result sequentially.
<
import "fmt"
Line 1,692:
fmt.Println(cartN(nil))
fmt.Println(cartN())
}</
{{out}}
<pre>
Line 1,735:
Code here is more compact, but with the cost of more garbage produced. It produces the same result as cartN above.
<
if len(a) == 0 {
return [][]int{nil}
Line 1,746:
}
return
}</
'''Extra credit 3'''
This is a compact recursive version like Extra credit 2 but the result list is ordered differently. This is still a correct result if you consider a cartesian product to be a set, which is an unordered collection. Note that the set elements are still ordered lists. A cartesian product is an unordered collection of ordered collections. It draws attention though to the gloss of using list representations as sets. Any of the functions here will accept duplicate elements in the input lists, and then produce duplicate elements in the result.
<
if len(a) == 0 {
return [][]int{nil}
Line 1,762:
}
return
}</
=={{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''.
<
static Iterable multiply(Iterable a, Iterable b) {
assert [a,b].every { it != null }
Line 1,773:
(0..<(m*n)).inject([]) { prod, i -> prod << [a[i.intdiv(n)], b[i%n]].flatten() }
}
}</
'''Test:'''<br>
The ''mixin'' method call is necessary to make the multiply (*) operator work.
<
println "\nCore Solution:"
Line 1,792:
println "[John,Paul,George,Ringo] × [Emerson,Lake,Palmer] × [Simon,Garfunkle] = ["
( ["John","Paul","George","Ringo"] * ["Emerson","Lake","Palmer"] * ["Simon","Garfunkle"] ).each { println "\t${it}," }
println "]"</
'''Output:'''
<pre>
Line 1,837:
Various routes can be taken to Cartesian products in Haskell.
For the product of two lists we could write:
<
cartProd xs ys =
[ (x, y)
| x <- xs
, y <- ys ]</
more directly:
<
cartProd xs ys = xs >>= \x -> ys >>= \y -> [(x, y)]</
applicatively:
<
cartProd xs ys = (,) <$> xs <*> ys</
parsimoniously:
<
cartProd = (<*>) . fmap (,)</
We might test any of these with:
<
main =
mapM_ print $
uncurry cartProd <$>
[([1, 2], [3, 4]), ([3, 4], [1, 2]), ([1, 2], []), ([], [1, 2])]</
{{Out}}
<pre>[(1,3),(1,4),(2,3),(2,4)]
Line 1,869:
For the n-ary Cartesian product of an arbitrary number of lists, we could apply the Prelude's standard '''sequence''' function to a list of lists,
<
cartProdN = sequence
main :: IO ()
main = print $ cartProdN [[1, 2], [3, 4], [5, 6]]</
{{Out}}
<pre>[[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2,3,5],[2,3,6],[2,4,5],[2,4,6]]</pre>
or we could define ourselves an equivalent function over a list of lists in terms of a fold, for example as:
<
cartProdN = foldr (\xs as -> xs >>= (<$> as) . (:)) [[]]</
or, equivalently, as:
<
cartProdN = foldr
(\xs as ->
Line 1,887:
| x <- xs
, a <- as ])
[[]]</
testing any of these with something like:
<
main = do
mapM_ print $
Line 1,896:
print $ cartProdN [[1,2,3], [30], [500, 100]]
putStrLn ""
print $ cartProdN [[1,2,3], [], [500, 100]]</
{{Out}}
<pre>[1776,7,4,0]
Line 1,929:
=={{header|J}}==
The J primitive [http://code.jsoftware.com/wiki/Vocabulary/curlylf catalogue] <code>{</code> forms the Cartesian Product of two or more boxed lists. The result is a multi-dimensional array (which can be reshaped to a simple list of lists if desired).
<
┌────────────┬────────────┐
│1776 7 4 0 │1776 7 4 1 │
Line 1,971:
└───────┴────────┘
{ 1 2 3 ; '' ; 50 100 NB. result is an empty 3-dimensional array with shape 3 0 2
</syntaxhighlight>
=={{header|Java}}==
{{works with|Java Virtual Machine|1.8}}
<
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
Line 2,004:
}
}
</syntaxhighlight>
'''Using a generic class with a recursive function'''
<
import java.util.ArrayList;
import java.util.Arrays;
Line 2,063:
}
}
</syntaxhighlight>
=={{header|JavaScript}}==
Line 2,071:
For the Cartesian product of just two lists:
<
// CARTESIAN PRODUCT OF TWO LISTS ---------------------
Line 2,086:
cartProd([])([1, 2]),
].map(JSON.stringify).join('\n');
})();</
{{Out}}
<pre>[[1,3],[1,4],[2,3],[2,4]]
Line 2,095:
Abstracting a little more, we can define the cartesian product quite economically in terms of a general applicative operator:
<
// CARTESIAN PRODUCT OF TWO LISTS ---------------------
Line 2,133:
.map(JSON.stringify)
.join('\n');
})();</
{{Out}}
<pre>[[1,3],[1,4],[2,3],[2,4]]
Line 2,141:
For the n-ary Cartesian product over a list of lists:
<
const main = () => {
// n-ary Cartesian product of a list of lists.
Line 2,201:
return main();
})();</
{{Out}}
<pre>[1776,7,4,0]
Line 2,235:
Imperative implementations of Cartesian products are inevitably less compact and direct, but we can certainly write an iterative translation of a fold over nested applications of '''bind''' or '''concatMap''':
<
// n-ary Cartesian product of a list of lists
// ( Imperative implementation )
Line 2,308:
]))
]);
})();</
{{Out}}
<pre>[[1,4],[1,3],[2,4],[2,3]]
Line 2,350:
jq is stream-oriented and so we begin by defining a function that will emit a stream of the elements of the Cartesian product of two arrays:
<syntaxhighlight lang=jq>
def products: .[0][] as $x | .[1][] as $y | [$x,$y];
</syntaxhighlight>
To generate an array of these arrays, one would in practice most likely simply write `[products]`, but to comply with the requirements of this article, we can define `product` as:
<syntaxhighlight lang=jq>
def product: [products];
</syntaxhighlight>
For the sake of brevity, two illustrations should suffice:
Line 2,372:
And
<syntaxhighlight lang=jq>
[[1,2], []] | product
</syntaxhighlight>
produces:
<pre>
Line 2,383:
Given an array of two or more arrays as input, `cartesians` as defined here produces a stream of the components of their Cartesian product:
<syntaxhighlight lang=jq>
def cartesians:
if length <= 2 then products
Line 2,390:
| [$x] + $y
end;
</syntaxhighlight>
Again for brevity, in the following, we will just show the number of items in the Cartesian products:
Line 2,405:
=={{header|Julia}}==
Run in REPL.
<
# Product {1, 2} × {3, 4}
collect(Iterators.product([1, 2], [3, 4]))
Line 2,422:
# Product {1, 2, 3} × {} × {500, 100}
collect(Iterators.product([1, 2, 3], [], [500, 100]))
</syntaxhighlight>
=={{header|Kotlin}}==
<
fun flattenList(nestList: List<Any>): List<Any> {
Line 2,477:
printNAryProduct(listOf(listOf(1, 2, 3), listOf<Int>(), listOf(500, 100)))
printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf('a', 'b')))
}</
{{out}}
Line 2,545:
{{works with|langur|0.8.3}}
<
writeln X([3, 4], [1, 2]) == [[3, 1], [3, 2], [4, 1], [4, 2]]
writeln X([1, 2], []) == []
Line 2,558:
writeln X [1, 2, 3], [], [500, 100]
writeln()</
{{out}}
Line 2,576:
=== Functional ===
An iterator is created to output the product items.
<
local getn = function(t)return #t end
local const = function(k)return function(e) return k end end
Line 2,625:
print(i,a,b)
end
</syntaxhighlight>
{{out}}
<pre>1 1 3
Line 2,641:
It is possible that specialising descend by depth may yield a further improvement in performance, but it would only be able to eliminate the lookup of ''sets[depth]'' and the if test, because the reference to ''result[depth]'' is required; I doubt the increase in complexity would be worth the (potential) improvement in performance.
<
local result = {}
local set_count = #sets
Line 2,689:
print(" " .. format_nested_list(product))
end
end</
=== Imperative iterator ===
The functional implementation restated as an imperative iterator, also adjusted to not allocate a new result table on each iteration; this saves time, but makes mutating the returned table unsafe.
<
local item_counts = {}
local indices = {}
Line 2,766:
print(i, format_nested_list(product))
end
end</
=== Functional-esque (non-iterator) ===
Motivation: If a list-of-lists is passed into the cartesian product, then wouldn't a list-of-lists be the expected return type? Of course this is just personal opinion/preference, other implementations are fine as-is if you'd rather have an iterator.
<
function T(t) return setmetatable(t, {__index=table}) end
table.clone = function(t) local s=T{} for k,v in ipairs(t) do s[k]=v end return s end
Line 2,801:
local cp = cartprod(test)
print("{"..cp:reduce(function(t,a) return (a=="" and a or a..", ").."("..t:concat(", ")..")" end,"").."}")
end</
{{out}}
<pre>{(1, 3), (1, 4), (2, 3), (2, 4)}
Line 2,812:
=={{header|Maple}}==
<
cartmulti := proc ()
local m, v;
Line 2,824:
end if;
end proc;
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 2,878:
ReadChar
END CartesianProduct.</
=={{header|Nim}}==
Line 2,888:
In order to display the result using mathematical formalism, we have created a special procedure “$$” for the sequences and have overloaded the procedure “$” for tuples.
<
# Yield the element of the cartesian product of "a" and "b".
# Yield tuples rather than arrays as it allows T1 and T2 to be different.
Line 2,927:
( Empty, @[1, 2])]:
echo &"{$$a} x {$$b} = {$$toSeq(product(a, b))}"</
{{out}}
Line 2,942:
Note that there exists in the standard module “algorithm” a procedure which computes the product of sequences of a same type. It is not recursive and, so, likely more efficient that the following version.
<
## Return the product of several sets (sequences).
Line 2,963:
b = @[3, 4]
c = @[5, 6]
echo &"{a} x {b} x {c} = {product(a, b, c)}"</
{{out}}
Line 2,973:
With a macro, we are able to mix several value types: the “varrags” is no longer a problem as being used at compile time it may contain sequences of different types. And we are able to return tuples of n values instead of sequences of n values.
<
macro product(args: varargs[typed]): untyped =
Line 3,046:
var b = @['a', 'b']
var c = @[false, true]
echo &"{$$a} x {$$b} x {$$c} = {$$product(a, b, c)}"</
{{out}}
Line 3,054:
''The double semicolons are necessary only for the toplevel''
Naive but more readable version<
match l1, l2 with
| [], _ | _, [] -> []
Line 3,067:
(*- : (int * 'a) list = []*)
product [] [1;2];;
(*- : ('a * int) list = []*)</
Implementation with a bit more tail-call optimization, introducing a helper function. The order of the result is changed but it should not be an issue for most uses.
<
let rec aux ~acc l1' l2' =
match l1', l2' with
Line 3,088:
(*- : (int * 'a) list = []*)
product' [] [1;2];;
(*- : ('a * int) list = []*)</
Implemented using nested folds:
<
List.fold_left (fun acc1 ele1 ->
List.fold_left (fun acc2 ele2 -> (ele1,ele2)::acc2) acc1 l2) [] l1 ;;
Line 3,097:
(*- : (int * char) list = [(3, 'c'); (3, 'b'); (3, 'a'); (2, 'c'); (2, 'b'); (2, 'a'); (1, 'c'); (1, 'b'); (1, 'a')]*)
cart_prod [1; 2; 3] [] ;;
(*- : ('a * int) list = [] *)</
Extra credit function. Since in OCaml a function can return only one type, and because tuples of different arities are different types, this returns a list of lists rather than a list of tuples. Since lists are homogeneous this version is restricted to products over a ''single'' type, eg integers.
<
(* We need to do the cross product of our current list and all the others
* so we define a helper function for that *)
Line 3,145:
*)
product'' [[1; 2; 3];[];[500; 100]];;
(*- : int list list = []*)</
=== Better type ===
In the latter example, our function has this signature:
<
This lacks clarity as those two lists are not equivalent since one replaces a tuple. We can get a better signature by creating a tuple type:
<
let rec product'' (l:'a list tuple) =
Line 3,173:
type 'a tuple = 'a list
val product'' : 'a list tuple -> 'a tuple list = <fun></
=={{header|Perl}}==
==== Iterative ====
Nested loops, with a short-circuit to quit early if any term is an empty set.
<
my $sets = shift @_;
for (@$sets) { return [] unless @$_ }
Line 3,209:
product([[1,2,3], [30], [500,100] ], '%1d %1d %3d' ).
product([[1,2,3], [], [500,100] ], '%1d %1d %3d' ).
product([[1776,1789], [7,12], [4,14,23], [0,1]], '%4d %2d %2d %1d')</
{{out}}
<pre>(1 3) (1 4) (2 3) (2 4)
Line 3,221:
==== Glob ====
This being Perl, there's more than one way to do it. A quick demonstration of how <code>glob</code>, more typically used for filename wildcard expansion, can solve the task.
<
for $a (@$tuples) { printf "(%1d %2d %3d) ", @$a; }</
{{out}}
<pre>(1 30 500) (1 30 100) (2 30 500) (2 30 100) (3 30 500) (3 30 100)</pre>
Line 3,229:
==== Modules ====
A variety of modules can do this correctly for an arbitrary number of lists (each of independent length). Arguably using modules is very idiomatic Perl.
<
forsetproduct { say "@_" } [1,2,3],[qw/a b c/],[qw/@ $ !/];
Line 3,239:
use Algorithm::Loops qw/NestedLoops/;
NestedLoops([[1,2,3],[qw/a b c/],[qw/@ $ !/]], sub { say "@_"; });</
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">cart</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 3,266:
<span style="color: #0000FF;">?</span><span style="color: #000000;">cart</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">30</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">500</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">100</span><span style="color: #0000FF;">}})</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">cart</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">},{},{</span><span style="color: #000000;">500</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">100</span><span style="color: #0000FF;">}})</span>
<!--</
{{out}}
<pre>
Line 3,282:
=={{header|Phixmonti}}==
<
def cart
Line 3,312:
( ( 1 2 ) ( ) ) cart
drop res print nl nl</
=={{header|PicoLisp}}==
<
(mapcan
'((I)
Line 3,340:
(cartesian (1 2 3) (30) (500 100)) )
(println
(cartesian (1 2 3) NIL (500 100)) )</
{{out}}
Line 3,352:
=={{header|Prolog}}==
<
product([A|_], Bs, [A, B]) :- member(B, Bs).
product([_|As], Bs, X) :- product(As, Bs, X).
</syntaxhighlight>
{{Out}}
<pre>
Line 3,372:
=={{header|Python}}==
===Using itertools===
<
def cp(lsts):
Line 3,386:
print(lists, '=>')
pp(cp(lists), indent=2)
</syntaxhighlight>
{{out}}
<pre>[[1, 2], [3, 4]] =>
Line 3,437:
If we write ourselves a re-usable Python '''ap''' function for the case of lists (applicative functions for other 'data containers' can also be written – this one applies a list of functions to a list of values):
<
def ap(fs):
return lambda xs: foldl(
lambda a: lambda f: a + foldl(
lambda a: lambda x: a + [f(x)])([])(xs)
)([])(fs)</
then one simple use of it will be to define the cartesian product of two lists (of possibly different type) as:
<syntaxhighlight lang
where Tuple is a constructor, and xs is bound to the first of two lists. The returned value is a function which can be applied to a second list.
Line 3,452:
For an nAry product, we can then use a '''fold''' (catamorphism) to lift the basic function over two lists ''cartesianProduct :: [a] -> [b] -> [(a, b)]'' to a function over a list of lists:
<
def nAryCartProd(xxs):
return foldl1(cartesianProduct)(
xxs
)</
For example:
<
Line 3,567:
# TEST ----------------------------------------------------
if __name__ == '__main__':
main()</
{{Out}}
<pre>Product of two lists of different types:
Line 3,606:
=={{header|Quackery}}==
<
swap witheach
[ over witheach
Line 3,618:
' [ 3 4 ] ' [ 1 2 ] cartprod echo cr
' [ 1 2 ] ' [ ] cartprod echo cr
' [ ] ' [ 1 2 ] cartprod echo cr</
{{out}}
Line 3,630:
=={{header|R}}==
<syntaxhighlight lang=R>
one_w_many <- function(one, many) lapply(many, function(x) c(one,x))
Line 3,648:
prod = Reduce( '%p%', list(...) )
display_prod( prod ) }
</syntaxhighlight>
Simple tests:
<syntaxhighlight lang=R>
> display_prod( c(1, 2) %p% c(3, 4) )
1, 3
Line 3,665:
> display_prod( c(3, 4) %p% c() )
>
</syntaxhighlight>
Tougher tests:
<syntaxhighlight lang=R>
go( c(1776, 1789), c(7, 12), c(4, 14, 23), c(0, 1) )
go( c(1, 2, 3), c(30), c(500, 100) )
go( c(1, 2, 3), c(), c(500, 100) )
</syntaxhighlight>
{{out}}
Line 3,718:
Racket has a built-in "cartesian-product" function:
<syntaxhighlight lang=text>#lang racket/base
(require rackunit
;; usually, included in "racket", but we're using racket/base so we
Line 3,734:
(cartesian-product '(1776 1789) '(7 12) '(4 14 23) '(0 1))
(cartesian-product '(1 2 3) '(30) '(500 100))
(cartesian-product '(1 2 3) '() '(500 100))</
{{out}}
Line 3,770:
The cross meta operator X will return the cartesian product of two lists. To apply the cross meta-operator to a variable number of lists, use the reduce cross meta operator [X].
<syntaxhighlight lang=raku
say (1, 2) X (3, 4);
say (3, 4) X (1, 2);
Line 3,780:
say [X] (1776, 1789), (7, 12), (4, 14, 23), (0, 1);
say [X] (1, 2, 3), (30), (500, 100);
say [X] (1, 2, 3), (), (500, 100);</
{{out}}
<pre>((1 3) (1 4) (2 3) (2 4))
Line 3,793:
===version 1===
This REXX version isn't limited by the number of lists or the number of sets within a list.
<
@.= /*assign the default value to @. array*/
parse arg @.1 /*obtain the optional value of @.1 */
Line 3,819:
end /*i*/
say 'Cartesian product of ' space(@.n) " is ───► {"substr($, 2)'}'
end /*n*/ /*stick a fork in it, we're all done. */</
{{out|output|text= when using the default lists:}}
<pre>
Line 3,830:
===version 2===
<
Call cart '{1, 2} x {3, 4}'
Call cart '{3, 4} x {1, 2}'
Line 3,893:
End
Say ' '
Return 0</
{{out}}
<pre>{1, 2} x {3, 4}
Line 3,951:
=={{header|Ring}}==
<
# Project : Cartesian product of two or more lists
Line 3,966:
next
see nl
</syntaxhighlight>
Output:
<pre>
Line 3,982:
=={{header|Ruby}}==
"product" is a method of arrays. It takes one or more arrays as argument and results in the Cartesian product:
<
p [3, 4].product([1, 2])
p [1, 2].product([])
Line 3,989:
p [1, 2, 3].product([30], [500, 100])
p [1, 2, 3].product([], [500, 100])
</syntaxhighlight>
{{out}}<pre>[[1, 3], [1, 4], [2, 3], [2, 4]]
[[3, 1], [3, 2], [4, 1], [4, 2]]
Line 4,000:
=={{header|Rust}}==
<
let mut res = vec![];
Line 4,041:
}
}
</syntaxhighlight>
{{out}}<pre>[1, 2] × [3, 4]
[[1, 3], [1, 4], [2, 3], [2, 4]]
Line 4,067:
Function returning the n-ary product of an arbitrary number of lists, each of arbitrary length:
<
/**
Line 4,096:
}
}
}</
and usage:
<
.map(_.mkString("(", ", ", ")")).mkString("{",", ","}")</
{{out}}
<pre>{(1, 3), (1, 4), (2, 3), (2, 4)}</pre>
<
.map(_.mkString("(", ", ", ")")).mkString("{",", ","}")</
{{out}}
<pre>{(3, 1), (3, 2), (4, 1), (4, 2)}</pre>
<
.map(_.mkString("(", ", ", ")")).mkString("{",", ","}")</
{{out}}
<pre>{}</pre>
<
.map(_.mkString("(", ", ", ")")).mkString("{",", ","}")</
{{out}}
<pre>{}</pre>
<
.map(_.mkString("(", ", ", ")")).mkString("{",", ","}")</
{{out}}
<pre>{(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>
<
.map(_.mkString("(", ", ", ")")).mkString("{",", ","}")</
{{out}}
<pre>{(1, 30, 500), (1, 30, 100), (2, 30, 500), (2, 30, 100), (3, 30, 500), (3, 30, 100)}</pre>
<
.map(_.mkString("[", ", ", "]")).mkString("\n")</
{{out}}
<pre>{}</pre>
=={{header|Scheme}}==
<
(define cartesian-product (lambda (xs ys)
(if (or (zero? (length xs)) (zero? (length ys)))
Line 4,155:
> (nary-cartesian-product '((1 2)(a b)(x y)))
((1 a x) (1 a y) (1 b x) (1 b y) (2 a x) (2 a y) (2 b x) (2 b y))
</syntaxhighlight>
=={{header|Sidef}}==
In Sidef, the Cartesian product of an arbitrary number of arrays is built-in as ''Array.cartesian()'':
<
cartesian([[1,2], [3,4], [5,6]], {|*arr| say arr })</
Alternatively, a simple recursive implementation:
<
var c = []
Line 4,182:
return r
}</
Completing the task:
<
say cartesian_product([3,4], [1,2])</
{{out}}
<pre>
Line 4,193:
</pre>
The product of an empty list with any other list is empty:
<
say cartesian_product([], [1,2])</
{{out}}
<pre>
Line 4,201:
</pre>
Extra credit:
<
{{out}}
<pre>
Line 4,230:
</pre>
<
say cartesian_product([1, 2, 3], [], [500, 100])</
{{out}}
<pre>
Line 4,240:
=={{header|SQL}}==
If we create lists as tables with one column, cartesian product is easy.
<
create table L1 (value integer);
insert into L1 values (1);
Line 4,249:
insert into L2 values (4);
-- get the product
select * from L1, L2;</
{{out}}
<pre> VALUE VALUE
Line 4,256:
1 4
2 3
2 4</pre>You should be able to be more explicit should get the same result:<
Product with an empty list works as expected (using the tables created above):
<
select * from L1, L2;</
{{out}}
<pre>no rows selected</pre>
I don't think "extra credit" is meaningful here because cartesian product is so hard-baked into SQL, so here's just one of the extra credit examples (again using the tables created above):<
insert into L2 values (30);
create table L3 (value integer);
Line 4,268:
insert into L3 values (100);
-- product works the same for as many "lists" as you'd like
select * from L1, L2, L3;</
{{out}}
<pre> VALUE VALUE VALUE
Line 4,280:
=={{header|Standard ML}}==
<
| prodList ((x::xs), ys) = map (fn y => (x,y)) ys @ prodList (xs, ys)
fun naryProdList zs = foldl (fn (xs, ys) => map op:: (prodList (xs, ys))) [[]] (rev zs)</
{{out}}
Line 4,312:
In Stata, the command '''[https://www.stata.com/help.cgi?fillin fillin]''' may be used to expand a dataset with all combinations of a number of variables. Thus it's easy to compute a cartesian product.
<
+-------+
Line 4,331:
3. | 2 3 1 |
4. | 2 4 0 |
+-----------------+</
The other way around:
<
+-------+
Line 4,354:
3. | 4 1 1 |
4. | 4 2 0 |
+-----------------+</
Note, however, that this is not equivalent to a cartesian product when one of the variables is "empty" (that is, only contains missing values).
<
+-------+
Line 4,375:
1. | 1 . 0 |
2. | 2 . 0 |
+-----------------+</
This command works also if the varaibles have different numbers of nonmissing elements. However, this requires additional code to remove the observations with missing values.
<
+-----------+
Line 4,434:
|---------------------|
6. | 3 5 6 1 |
+---------------------+</
=={{header|Swift}}==
Line 4,440:
{{trans|Scala}}
<
var ret = arr
Line 4,482:
print(cartesianProduct([1776, 1789], [7, 12], [4, 14, 23], [0, 1]))
print(cartesianProduct([1, 2, 3], [30], [500, 100]))
print(cartesianProduct([1, 2, 3], [], [500, 100])</
{{out}}
Line 4,494:
=={{header|Tailspin}}==
<
'{1,2}x{3,4} = $:[by [1,2]..., by [3,4]...];
' -> !OUT::write
Line 4,519:
'year {1776, 1789} × month {7, 12} × day {4, 14, 23} = $:{by [1776, 1789]... -> (year:$), by [7, 12]... -> (month:$), by [4, 14, 23]... -> (day:$)};
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 4,533:
=={{header|Tcl}}==
<
proc cartesianProduct {l1 l2} {
set result {}
Line 4,569:
puts "result: [cartesianNaryProduct {{1 2 3} {} {500 100}}]"
</syntaxhighlight>
{{out}}
<pre>
Line 4,628:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Module Module1
Line 4,664:
End Sub
End Module</
{{out}}
<pre>{(1, 3), (1, 4), (2, 3), (2, 4)}
Line 4,677:
{{trans|Kotlin}}
{{libheader|Wren-seq}}
<
var prod2 = Fn.new { |l1, l2|
Line 4,709:
printProdN.call([ [1, 2, 3], [30], [500, 100] ])
printProdN.call([ [1, 2, 3], [], [500, 100] ])
printProdN.call([ [1, 2, 3], [30], ["a", "b"] ])</
{{out}}
Line 4,776:
Cartesian product is build into iterators or can be done with nested
loops.
<
L(L(1,3),L(1,4),L(2,3),L(2,4))
zkl: foreach a,b in (List(1,2),List(3,4)){ print("(%d,%d) ".fmt(a,b)) }
Line 4,782:
zkl: Walker.cproduct(List(3,4),List(1,2)).walk().println();
L(L(3,1),L(3,2),L(4,1),L(4,2))</
The walk method will throw an error if used on an empty iterator but the pump
method doesn't.
<
Exception thrown: TheEnd(Ain't no more)
Line 4,792:
L()
zkl: Walker.cproduct(List,List(3,4)).pump(List).println();
L()</
<
L(L(1776,7,4,0),L(1776,7,4,1),L(1776,7,14,0),L(1776,7,14,1),L(1776,7,23,0),L(1776,7,23,1),L(1776,12,4,0),L(1776,12,4,1),L(1776,12,14,0),L(1776,12,14,1),L(1776,12,23,0),L(1776,12,23,1),L(1789,7,4,0),L(1789,7,4,1),L(1789,7,14,0),L(1789,7,14,1),L(1789,7,23,0),L(1789,7,23,1),L(1789,12,4,0),L(1789,12,4,1),...)
Line 4,800:
zkl: Walker.cproduct(L(1,2,3),List,L(500,100)).pump(List).println();
L()</
|