DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge: Rotating the hex

Weekly Challenge 402

Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. Unless otherwise stated, Copilot (and other AI tools) have NOT been used to generate the solution. It's a great way for us all to practice some coding.

Challenge, My solutions

Task 1: Letters Only Hex

You are given a string representing a decimal integer >= 1 without leading zeros.

Write a script that 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.

My solution

This is relatively straight forward so doesn't need much explanation. I use the hex function to convert the integer to its hexadecimal representation (striping off the leading 0x). I then check that it only contains letters or 0 or 1. Finally, I convert the string to upper case and replace 0 and 1 with O and I respectively.

def letter_only_hex(n: int) -> str:
    hex_string = hex(n)[2:]

    if not re.search(r"^[01a-f]+$", hex_string):
        return ""

    return hex_string.upper().replace("0", "O").replace("1", "I")
Enter fullscreen mode Exit fullscreen mode

In Perl, the hex function actually does the opposite, that is it converts a hex string to an integer. Thankfully, sprintf allows us to convert a number to a hex value. This also has a caveat that it will produce an incorrect result if the integer is greater than 18,446,744,073,709,551,615 (264-1). The tr function allows us to convert both numbers in a single call.

sub main ($expr) {
    my $hex_string = sprintf '%x', $expr;

    if ( $hex_string !~ /^[01a-f]+$/ ) {
        say '""';
    }
    else {
        $hex_string =~ tr/01/OI/;
        say '"' . uc($hex_string) . '"';
    }
}
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py 16
"IO"

$ ./ch-1.py 10
"A"

$ ./ch-1.py 2748
"ABC"

$ ./ch-1.py 4098
""

$ ./ch-1.py 68719476735
"FFFFFFFFF"
Enter fullscreen mode Exit fullscreen mode

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.

My solution

This is also relatively straight forward. For input from the command, I take the first value as the input_string variable and subsequent values as pairs that make up the directions variable.

Rather than do all the rotations, its easier to calculate the final right rotations. For the Python method, I use list comprehension to calculate this. The last step is to return the string sliced at the appropriate position.

def circular_string_rotations(input_string: str, directions: list[list[int]]) -> str:
    str_len = len(input_string)
    final_moves = sum(0 - d[1] if d[0] else d[1] for d in directions) % str_len

    return input_string[final_moves:] + input_string[:final_moves]
Enter fullscreen mode Exit fullscreen mode

The Perl solution follows similar logic, using the map function to calculate the offset.

use List::Util qw(pairs sum);

sub main ( $input_string, @args ) {
    # Turn the inputs to pairs
    my @directions  = pairs(@args);

    # Calculate the final number of moves to the right
    my $final_moves = sum(map { $_->[0] ? 0 - $_->[1] : $_->[1] } @directions);
    $final_moves = $final_moves % length($input_string);

    # Return the shifted string
    say substr( $input_string, $final_moves )
      . substr( $input_string, 0, $final_moves );
}
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py hello 1 3 0 3
hello

$ ./ch-2.py abcd 1 6
cdab

$ ./ch-2.py coding 0 4 1 2
dingco

$ ./ch-2.py planet 0 11 1 4 0 2
netpla

$ ./ch-2.py z 0 5 1 9
z

$ ./ch-2.py jubilee 0 12 1 3 0 9
leejubi
Enter fullscreen mode Exit fullscreen mode

Top comments (0)