I’ve been doing the Weekly
Challenges. The
latest
involved base conversion and string rotation. (Note that this ends
today.)
Task 1: Letters Only Hex
You are given a string representing a decimal integer ≥ 1 without
leading zeros.
Write a script to convert the given string into its uppercase
hexadecimal representation. Replace every digit '0' with the letter
'O', also replace every digit '1' with the letter 'I'. The resulting
string should only contain characters: 'A', 'B', 'C', 'D', 'E', 'F',
'I', and 'O'.
Several of the languages I'm using have base conversions built in, but
given that I'm adjusting the characters anyway…
Raku
sub lettersonlyhex($a0) {
Get the string into a number.
my $a = 0 + $a0;
my @v;
Loop extracting hex digits (in reverse order).
loop {
my $d = $a % 16;
If they're valid, push them on to the start of the output list.
if ($d >= 10) {
@v.unshift(chr(55 + $d));
} elsif ($d == 0) {
@v.unshift("O");
} elsif ($d == 1) {
@v.unshift("I");
Otherwise, bail out now.
} else {
return "";
}
$a div= 16;
if ($a == 0) {
last;
}
}
Return the output list as a string.
@v.join('');
}
Task 2: Circular String Rotations
You are given a string containing lowercase English letters and
directions array in the form [direction, amount]. The direction 0 is
left shift and direction 1 is right shift.
Write a script to apply the sequence of left and right rotations to
the given string and return the final string.
I think the important thing here is to do just one string rotation.
In Perl:
Add up all the numbers (positive and negative).
sub circularstringrotations($st, $dir) {
my $roll = 0;
foreach my $v (@{$dir}) {
if ($v->[0] == 0) {
$roll += $v->[1];
} else {
$roll -= $v->[1];
}
}
Constrain the total into 0 .. (string length - 1). (Euclidean
remainder, but many languages allow it to become negative.)
$roll %= length($st);
while ($roll < 0) {
$roll += length($st);
}
Double the input string.
my $s1 = $st . $st;
Offset into it to get the output.
substr($s1, $roll, length($st));
}
Full code in all tagged languages is on
codeberg.