Permutations/Derangements: Difference between revisions

Line 2,166:
{{trans|Perl}}
{{works with|Rakudo|2016.10}}
 
 
Generate <code>List.permutations</code> and keep the ones where no elements are in their original position. This is done by zipping each permutation with the original list, and keeping the ones where none of the zipped pairs are equal.
 
I am using the <code>Z</code> infix zip operator with the <code>eqv</code> equivalence infix operator, all wrapped inside a <code>none()</code> Junction.
 
Although not necessary for this task, I have used <code>eqv</code> instead of <code>==</code> so that the <code>derangements()</code> function also works with any set of arbitrary objects (eg. strings, lists, etc.)
 
<lang perl6>sub derangements(@l) {
Line 2,178 ⟶ 2,185:
say derangements([1, 2, 3, 4]), "\n";
 
say 'n == !n == derangements(1 .. ^n).elems';
for 0 .. 9 -> $n {
say "!$n == { !$n } == { derangements(1 .. ^$n).elems }"
}</lang>
{{out}}
Line 2,187 ⟶ 2,194:
((2 1 4 3) (2 3 4 1) (2 4 1 3) (3 1 4 2) (3 4 1 2) (3 4 2 1) (4 1 2 3) (4 3 1 2) (4 3 2 1))
 
n == !n == derangements(1 .. ^n).elems
!0 == 1 == 1
!1 == 0 == 0
Anonymous user