Raku challenge Week 70, issue 1

Here is a program in Raku to solve the task 1 of the weekly challenge. An interesting thing here is a reminder of how you swap the two elements of an array.

Here is a solution and some comments to the Task 1 of the Perl Weekly Challenge Week 70.

The original task is the following:

You are given a string $S of size $N.

You are also given swap count $C and offset $O such that $C >= 1, $O >= 1 and $C + $O <= $N.

Write a script to perform character swapping like below:

$S[ 1 % $N ] <=> $S[ (1 + $O) % $N ]
$S[ 2 % $N ] <=> $S[ (2 + $O) % $N ]
$S[ 3 % $N ] <=> $S[ (3 + $O) % $N ]
...
...
$S[ $C % $N ] <=> $S[ ($C + $O) % $N ]

A couple of comments. First, notice that the first character of the string can be changed only if $S + $O == $N. Second, there is no need to make a modulo operation for $C as it is always lower than $N according to the initial conditions.

The most interesting part is swapping the two characters. It is simpler to work with an array, so we first split the string into characters and then join them back. To swap the two elements of an array, you can write:

@s[$x, $y] = @s[$y, $x]

Finally, here is the whole program:

my $s = 'perlandraku';
my $c = 3;
my $o = 4;

my @s = $s.comb;
for 1..$c -> $x {
    my $y = ($x + $o) % $s.chars;
    @s[$x, $y] = @s[$y, $x];
}
$s = @s.join('');

say $s;

Run it with different values of the initial values. For the given defaults, the program prints:

$ raku ch-1.raku 
pndraerlaku

→ GitHub repository
→ Navigation to the Raku challenges post series

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code