Permutations: Difference between revisions

Content added Content deleted
Line 3,011: Line 3,011:
2 0 1
2 0 1
2 1 0</pre>
2 1 0</pre>

=={{header|Phix}}==
The distribution includes builtins\permute.e, which is reproduced below. This can be used to retrieve all possible permutations, in
no particular order. The elements can be any type. It is just as fast to generate the (n!)th permutation as the first, so some applications may benefit by storing
an integer key rather than duplicating all the elements of the given set.
<lang Phix>global function permute(integer n, sequence set)
--
-- return the nth permute of the given set.
-- n should be an integer in the range 1 to factorial(length(set))
--
sequence res
integer w
n -= 1
res = set
for i=length(set) to 1 by -1 do
w = remainder(n,i)+1
res[i] = set[w]
set[w] = set[i]
n = floor(n/i)
end for
return res
end function</lang>
Example use:
<lang Phix>function permutes(sequence set)
sequence res = repeat(0,factorial(length(set)))
for i=1 to length(res) do
res[i] = permute(i,set)
end for
return res
end function
?permutes("abcd")</lang>
{{out}}
<pre>
{"bcda","dcab","bdac","bcad","cdba","cadb","dabc","cabd","bdca","dacb","badc","bacd","cbda","cdab","dbac","cbad","dcba","acdb","adbc","acbd","dbca","adcb","abdc","abcd"}
</pre>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==