Cartesian product of two or more lists: Difference between revisions
Content added Content deleted
Line 441: | Line 441: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
<lang lisp>(defun cartesian-product (s1 s2) |
|||
"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)))) |
|||
</lang> |
|||
'''Output''' |
|||
<lang lisp> |
|||
CL-USER> (cartesian-product '(1 2) '(3 4)) |
|||
((1 3) (1 4) (2 3) (2 4)) |
|||
CL-USER> (cartesian-product '(3 4) '(1 2)) |
|||
((3 1) (3 2) (4 1) (4 2)) |
|||
CL-USER> (cartesian-product '(1 2) '()) |
|||
NIL |
|||
CL-USER> (cartesian-product '() '(1 2)) |
|||
NIL |
|||
</lang> |
|||
<lang lisp>(defun n-cartesian-product (l) |
<lang lisp>(defun n-cartesian-product (l) |
||
"Compute the n-cartesian product of a list of sets represented as list with a mixed recursive-iterative approach. |
"Compute the n-cartesian product of a list of sets represented as list with a mixed recursive-iterative approach. |