How to resolve the algorithm Permutations by swapping step by step in the Raku programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Permutations by swapping step by step in the Raku programming language
Table of Contents
Problem Statement
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation here. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Permutations by swapping step by step in the Raku programming language
Source code in the raku programming language
sub insert($x, @xs) { ([flat @xs[0 ..^ $_], $x, @xs[$_ .. *]] for 0 .. +@xs) }
sub order($sg, @xs) { $sg > 0 ?? @xs !! @xs.reverse }
multi perms([]) {
[] => +1
}
multi perms([$x, *@xs]) {
perms(@xs).map({ |order($_.value, insert($x, $_.key)) }) Z=> |(+1,-1) xx *
}
.say for perms([0..2]);
You may also check:How to resolve the algorithm Sum and product of an array step by step in the Raku programming language
You may also check:How to resolve the algorithm FizzBuzz step by step in the Elm programming language
You may also check:How to resolve the algorithm Run-length encoding step by step in the Objective-C programming language
You may also check:How to resolve the algorithm CRC-32 step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Formatted numeric output step by step in the Scala programming language