📘 How to randomise an array in Perl 6

Shuffle the elements of an array in random order. Arrays in Perl 6 have the pick method, which does the work. my @a = 1..20;say@a.pick(@a); A possible output of the program looks like this: (4 18 10 15 14 8 2 11 3 12 1 6 9 19 13 7 16 17 20 5) The pick method … Continue reading “📘 How to randomise an array in Perl 6”

📘 How to rotate a list in Perl 6

Move all elements of an array N positions to the left or to the right. Array is a data type in Perl 6 that offers the rotate method, which does exactly what is needed. It takes an argument that tells the length and direction of the rotation. my @a = (1, 3, 5, 7, 9, 11, … Continue reading “📘 How to rotate a list in Perl 6”

📘 How to reverse a list in Perl 6

Print the given list in reverse order. Start with an array of integer numbers. my @a = (10, 20, 30, 40, 50); To reverse the array, call the reversemethod on it. say @a.reverse; This line prints the required result: (50 40 30 20 10) Notice that the initial array stays unchanged. The reversemethod creates a new sequence … Continue reading “📘 How to reverse a list in Perl 6”

📘 Swap two values in Perl 6

Swap the values of two variables. In Perl 6, there is no need to use temporary variables to swap the values of two variables. Just use the lists on both sides of the equation: ($b, $a) = ($a, $b); Alternatively, call the reverse method and assign the result back to the values: ($a, $b).=reverse; Consider the … Continue reading “📘 Swap two values in Perl 6”