How to resolve the algorithm Permutations/Derangements step by step in the Raku programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Permutations/Derangements step by step in the Raku programming language
Table of Contents
Problem Statement
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. There are various ways to calculate !n.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Permutations/Derangements step by step in the Raku programming language
Source code in the raku programming language
sub derangements(@l) {
@l.permutations.grep(-> @p { none(@p Zeqv @l) })
}
sub prefix:(Int $n) {
(1, 0, 1, -> $a, $b { ($++ + 2) × ($b + $a) } ... *)[$n]
}
say 'derangements([1, 2, 3, 4])';
say derangements([1, 2, 3, 4]), "\n";
say 'n == !n == derangements(^n).elems';
for 0 .. 9 -> $n {
say "!$n == { !$n } == { derangements(^$n).elems }"
}
You may also check:How to resolve the algorithm Intersecting number wheels step by step in the REXX programming language
You may also check:How to resolve the algorithm Loops/While step by step in the AWK programming language
You may also check:How to resolve the algorithm Multiple regression step by step in the zkl programming language
You may also check:How to resolve the algorithm Check that file exists step by step in the Elixir programming language
You may also check:How to resolve the algorithm Fortunate numbers step by step in the Phix programming language