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