Permutations: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 6,603: | Line 6,603: | ||
perms([1, 2, 3]) // [[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]]</lang> |
perms([1, 2, 3]) // [[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]]</lang> |
||
=={{header|Tailspin}}== |
|||
<lang tailspin> |
|||
templates permutations |
|||
<1> [1] ! |
|||
<> |
|||
def n: $it |
|||
templates expand |
|||
def p: $it |
|||
1..$n -> (def k: $it |
|||
[$p(1..$k-1)..., $n, $p($k..-1)...] !) ! |
|||
end expand |
|||
$n - 1 -> permutations -> expand ! |
|||
end permutations |
|||
def alpha: ['ABCD'...] |
|||
[ $alpha::length -> permutations -> '$($alpha($it)...)' ] -> stdout |
|||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
[DCBA, CDBA, CBDA, CBAD, DBCA, BDCA, BCDA, BCAD, DBAC, BDAC, BADC, BACD, DCAB, CDAB, CADB, CABD, DACB, ADCB, ACDB, ACBD, DABC, ADBC, ABDC, ABCD] |
|||
</pre> |
|||
With a little more careful work we can output permutations in lexical order |
|||
<lang tailspin> |
|||
templates lexicalPermutations |
|||
<1> [1] ! |
|||
<> |
|||
def n: $it |
|||
def p: [ $n - 1 -> lexicalPermutations ] |
|||
1..$n -> (def k: $it |
|||
def tail: [1..$n -> (<~$k> $it !)] |
|||
$p... -> [ $k, $tail($it)...] !) ! |
|||
end lexicalPermutations |
|||
def alpha: ['ABCD'...] |
|||
[ $alpha::length -> lexicalPermutations -> '$($alpha($it)...)' ] -> stdout |
|||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
[ABCD, ABDC, ACBD, ACDB, ADBC, ADCB, BACD, BADC, BCAD, BCDA, BDAC, BDCA, CABD, CADB, CBAD, CBDA, CDAB, CDBA, DABC, DACB, DBAC, DBCA, DCAB, DCBA] |
|||
</pre> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |