Permutations: Difference between revisions

Content added Content deleted
(→‎{{header|Mathematica}}: added version defining permutations from scratch)
Line 3,790: Line 3,790:


=={{header|Mathematica}}==
=={{header|Mathematica}}==
Version from scratch:

<lang Mathematica>
(***Standard list functions:*)
fold[f_, x_, {}] := x
fold[f_, x_, {h_, t___}] := fold[f, f[x, h], {t}]
insert[L_, x_, n_] := Join[L[[;; n - 1]], {x}, L[[n ;;]]]

(***Generate all permutations of a set S:*)

permutations[S_] :=
fold[Join @@ (Function[{L},
Table[insert[L, #2, k + 1], {k, 0, Length[L]}]] /@ #1) &, {{}},
S]
</lang>

Built-in version:
<lang Mathematica>Permutations[{1,2,3,4}]</lang>
<lang Mathematica>Permutations[{1,2,3,4}]</lang>
{{out}}
{{out}}