5
$\begingroup$

Here you see how to produce a cartesian product of two sets. How can we obtain the cartesian product of three or more sets? CartesianProduct[l1,l2,l3] doesn't work.

$\endgroup$
3
  • 1
    $\begingroup$ Flatten /@ CartesianProduct[CartesianProduct[list1, list2], list 3]? $\endgroup$
    – march
    Commented Sep 29, 2017 at 19:02
  • 2
    $\begingroup$ Have you seen Tuples[]? $\endgroup$ Commented Sep 29, 2017 at 19:02
  • 1
    $\begingroup$ @J.M. Of course! Tuples[{S, S, S}] did the trick. Thanks :-) $\endgroup$
    – Filburt
    Commented Sep 29, 2017 at 19:12

2 Answers 2

6
$\begingroup$

As @JM said, use Tuples[{set1, set2, set3, ...}].

CartiesianProduct is part of the obsolete and underdocumented Combinatorica package. Try to avoid this package unless you cannot find some functionality elsewhere.

If set1, set2 are lists the example look like the following:

In: Tuples[{{a, b}, {c, d}}]

Out: {{a, c}, {a, d}, {b, c}, {b, d}}
$\endgroup$
3
$\begingroup$

You can also use Distribute:

cpF = Distribute[{##}, List] &;

cpF[{a, b}, {u, v}, {r, s, t}]

{{a, u, r}, {a, u, s}, {a, u, t},
{a, v, r}, {a, v, s}, {a, v, t},
{b, u, r}, {b, u, s}, {b, u, t},
{b, v, r}, {b, v, s}, {b, v, t}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.