Perl Weekly Challenge: Where it stops, nobody knows!

Perl Weekly Challenge 402‘s tasks are “Letters Only Hex” and “Circular String Rotations”.

When I looked at what the second problem did, I immediately heard lyrics in my head: “My situation goes ’round and ’round (‘Round and ’round)“.

So let’s heat up and cool down with this week’s challenge…

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’.

Example 1

Input: $expr = "16"
Output: "IO"

Example 2

Input: $expr = "10"
Output: "A"

Example 3

Input: $expr = "2748"
Output: "ABC"

Example 4

Input: $expr = "4098"
Output: ""

Hex equivalent: 1002 => IOO2
Mostly valid characters (1, 0, 0), but fails because of a single '2'.

Approach

The first step in this is figuring out what it’s asking for. I think this is asking me to convert the string number into its hex equivalent, and then push it through a conversion so there’s only letters. Let’s look at the first example.

“16” in hex is “10”, which when we follow the substitution rules becomes “IO”.

“10” in hex is “A”. No substitutions are needed.

“2748” in hex is “ABC”. No substitutions are needed.

“4098” in hex is “1002”, and the example shows that it rejects the conversion because it can’t translate the digit 2″.

So I was right about what it’s asking me to do. So the way to do it is to make the string into an integer, convert that integer to base 16, transliterate the 0s and 1s to Os and Is, and then spit out the resulting string if it doesn’t contain any non-alphabetic characters.

Raku

We’re using Real.base to convert the number back to a string in base-16. Back in PWC 399, I was hoping I could use the Str.trans method to count tabs as I eliminated them, and I couldn’t do that, but this time, I don’t need to count… I just need to transliterate.

sub lettersOnlyHex($expr) {
  my $out = $expr.Int.base(16).Str.trans('0' => "O", "1" => "I");
  $out ~~ /^<[ABCDEFIO]>+$/ ?? $out !! "";
} 

View the entire Raku script for this task on GitHub.

$ raku/ch-1.raku
Example 1
Input: $expr = "16"
Output: "IO"

Example 2
Input: $expr = "10"
Output: "A"

Example 3
Input: $expr = "2748"
Output: "ABC"

Example 4
Input: $expr = "4098"
Output: ""

Example 5
Input: $expr = "68719476735"
Output: "FFFFFFFFF"

Perl

Perldoc suggests that if we want to present something as hex, we should use sprintf; and, once again, we’re using the /r modifier to non-destructively substitute values and return the new value.

sub lettersOnlyHex($expr) {
  my $out = (sprintf "%X", $expr) =~ tr/01/OI/r;
  $out =~ /^[ABCDEFIO]+$/ ? $out : "";
}

View the entire Perl script for this task on GitHub.

Python

Python is similar, in that we’re using string formatting to convert the integer value to base-16, and then we’re using str.maketrans() and str.translate() to do the string transliteration. Rather than use a regular expression, however, I decided to loop through the characters in the result string, and if they weren’t in the list of allowed characters, return the empty string.

def letters_only_hex(expr):
  out = ('%X' % int(expr)).translate(str.maketrans("01", "OI"))
  for letter in out:
    if letter not in "ABCDEFIO":
      return ""
  return out

View the entire Python script for this task on GitHub.

Elixir

As usual, I had fun n Elixir making it a pipe. String.replace/4 was a little frustrating in that I could specify a list for the pattern being matched, but for the replacement, it was either a single string, or a function that accepted the character that was matched and returned the replacement character.

def letters_only_hex(expr) do
  expr
  |> String.to_integer()
  |> Integer.to_string(16)
  |> String.replace(
    ["0", "1"],
    &if(&1 == "0", do: "O", else: "I")
  )
  |> then(&if &1 =~ ~r/^[ABCDEFIO]+$/, do: &1, else: "")
end

View the entire Elixir script for this task on GitHub.


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.

Example 1

Input: $str = "hello"
       @directions = ([1, 3], [0, 3])
Output: "hello"

Operation 1: [1,3]
Right 1: "ohell"
Right 2: "lohel"
Right 3: "llohe"

Operation 2: [0, 3]
Left 1: "lohel"
Left 2: "ohell"
Left 3: "hello"

Example 2

Input: $str = "abcd"
       @directions = ([1, 6])
Output: "cdab"

Operation 1: [1,6]
Right 1: "dabc"
Right 2: "cdab"
Right 3: "bcda"
Right 4: "abcd"
Right 5: "dabc"
Right 6: "cdab"

Example 3

Input: $str = "coding"
       @directions = ([0, 4], [1, 2])
Output: "dingco"

Operation 1: [0,4]
Left 1: "odingc"
Left 2: "dingco"
Left 3: "ingcod"
Left 4: "ngcodi"

Operation 2: [1,2]
Right 1: "ingcog"
Right 2: "dingco"

Example 4

Input: $str = "planet"
       @directions = ([0, 11], [1, 4], [0, 2])
Output: "netpla"

Example 5

Input: $str = "z"
       @directions = ([0, 5], [1, 9])
Output: "z"

Example 6

Input: $str = "jubilee"
       @directions = ([0, 12], [1, 3], [0, 9])
Output: "leejubi"

Approach

This problem is straightforward: take string, rotate the characters as specified by @directions, and spit out the string.

Raku

In Raku, I knew I wanted to use List.rotate to do the rotation, which meant I needed to convert the string to a List first, but that made operating on the characters easier anyway. I’m also using .= to assign the value of the rotation back to the @chars list before joining them back together to document the steps. If I weren’t generating the intermediate steps, lines 11-13 could just be @chars.=rotate($times) and lines 16-18 could be @chars.=rotate($times * -1). In fact, if I didn’t want to generate the intermediate steps, the entire solution would be

sub circularStringRotations($str, @directions) {
  my @chars = $str.comb;
  while @directions.shift -> ($dir, $times) {
    my $t = ($dir == 0) ?? $times !! $times * -1;
    @chars.=rotate($t);
  }
  @chars.join
}

But I do want to produce those steps, so…

sub circularStringRotations($str, @directions) {
  my @shifts;
  my $count = 1;
  my @chars = $str.comb;
  while @directions.shift -> ($dir, $times) {
    @shifts.push("\nOperation: $count: [$dir,$times]");
    if ($dir == 0) { # rotate left
      for 1 .. $times -> $i {
        @shifts.push("Left $i: " ~ @chars.=rotate(1).join);
      }
    }
    else { # rotate right
      for 1 .. $times -> $i {
        @shifts.push("Right $i: " ~ @chars.=rotate(-1).join);
      }
    }
    $count++;
  }
  @chars.join, @shifts
}

View the entire Raku script for this task on GitHub.

$ raku/ch-2.raku
Example 1
Input: $str = "hello"
       @directions = ([1, 3], [0, 3])
Output: "hello"

Operation: 1: [1,3]
Right 1: ohell
Right 2: lohel
Right 3: llohe

Operation: 2: [0,3]
Left 1: lohel
Left 2: ohell
Left 3: hello

Example 2
Input: $str = "abcd"
       @directions = ([1, 6])
Output: "cdab"

Operation: 1: [1,6]
Right 1: dabc
Right 2: cdab
Right 3: bcda
Right 4: abcd
Right 5: dabc
Right 6: cdab

Example 3
Input: $str = "coding"
       @directions = ([0, 4], [1, 2])
Output: "dingco"

Operation: 1: [0,4]
Left 1: odingc
Left 2: dingco
Left 3: ingcod
Left 4: ngcodi

Operation: 2: [1,2]
Right 1: ingcod
Right 2: dingco

Example 4
Input: $str = "planet"
       @directions = ([0, 11], [1, 4], [0, 2])
Output: "netpla"

Operation: 1: [0,11]
Left 1: lanetp
Left 2: anetpl
Left 3: netpla
Left 4: etplan
Left 5: tplane
Left 6: planet
Left 7: lanetp
Left 8: anetpl
Left 9: netpla
Left 10: etplan
Left 11: tplane

Operation: 2: [1,4]
Right 1: etplan
Right 2: netpla
Right 3: anetpl
Right 4: lanetp

Operation: 3: [0,2]
Left 1: anetpl
Left 2: netpla

Example 5
Input: $str = "z"
       @directions = ([0, 5], [1, 9])
Output: "z"

Operation: 1: [0,5]
Left 1: z
Left 2: z
Left 3: z
Left 4: z
Left 5: z

Operation: 2: [1,9]
Right 1: z
Right 2: z
Right 3: z
Right 4: z
Right 5: z
Right 6: z
Right 7: z
Right 8: z
Right 9: z

Example 6
Input: $str = "jubilee"
       @directions = ([0, 12], [1, 3], [0, 9])
Output: "leejubi"

Operation: 1: [0,12]
Left 1: ubileej
Left 2: bileeju
Left 3: ileejub
Left 4: leejubi
Left 5: eejubil
Left 6: ejubile
Left 7: jubilee
Left 8: ubileej
Left 9: bileeju
Left 10: ileejub
Left 11: leejubi
Left 12: eejubil

Operation: 2: [1,3]
Right 1: leejubi
Right 2: ileejub
Right 3: bileeju

Operation: 3: [0,9]
Left 1: ileejub
Left 2: leejubi
Left 3: eejubil
Left 4: ejubile
Left 5: jubilee
Left 6: ubileej
Left 7: bileeju
Left 8: ileejub
Left 9: leejubi

Perl

Perl doesn’t have a rotate method, but it does have a splice function and that lets us do pretty much the same thing.

sub circularStringRotations($str, @directions) {
  my @shifts;
  my $count = 1;
  my @chars = split //, $str;
  while (my $op = shift @directions) {
    my ($dir, $times) = @$op;
    push @shifts, "\nOperation: $count: [$dir,$times]";
    if ($dir == 0) { # rotate left
      for my $i (1 .. $times) {
        @chars = (splice(@chars,1), $chars[0]);
        push @shifts, "Left $i: " . join("", @chars);
      }
    }
    else { # rotate right
      for my $i (1 .. $times) {
        @chars = ($chars[-1], splice(@chars,0,-1));
        push @shifts, "Right $i: " . join("", @chars);
      }
    }
    $count++;
  }
  join("", @chars), \@shifts
}

View the entire Perl script for this task on GitHub.

Python

The big change in the Python solution is, because pulling out string slices is so easy, I never converted the string to a list: I just operated on the list directly.

def circular_string_rotations(string, directions):
  shifts = []
  count = 1
  while directions:
    d, times = directions.pop(0)
    shifts.append(f'\nOperation {count}: [{d},{times}]')
    count += 1
    if d == 0: # rotate left
      for i in range(1, times+1):
        string = string[1:] + string[0:1]
        shifts.append(f'Left {i}: {string}')
    else: # rotate right
      for i in range(1, times+1):
        string = string[-1:] + string[0:-1]
        shifts.append(f'Right {i}: {string}')
  return string, shifts

View the entire Python script for this task on GitHub.

Elixir

But in Elixir, I stuck with operating on lists, because Kernel.hd/1, Kernel.tl/1, and List.pop_at/3 made it easy to splice the lists. I did swap the order of the directions and string parameters, however, so I could keep the list being consumed by the recursive call first in the parameter list.

import Enum

def circular_string_rotations(dir, str, c \\ 1, s \\ [])

def circular_string_rotations([], str, _count, shifts),
  do: {str, shifts}

def circular_string_rotations(
      [[d, t] | dir],
      str,
      count,
      shifts
    ) do
  shifts = shifts ++ ["\nOperation #{count}: [#{d},#{t}]"]
  str = str |> String.graphemes()

  {str, shifts} =
    if d == 0 do
      # rotate left
      reduce(1..t, {str, shifts}, fn i, {str, shifts} ->
        str = tl(str) ++ [hd(str)]
        shifts = shifts ++ ["Left #{i}: #{join(str)}"]
        {str, shifts}
      end)
    else
      # rotate right
      reduce(1..t, {str, shifts}, fn i, {str, shifts} ->
        {last, rest} = List.pop_at(str, -1)
        str = [last] ++ rest
        shifts = shifts ++ ["Right #{i}: #{join(str)}"]
        {str, shifts}
      end)
    end

  circular_string_rotations(dir, join(str), count + 1, shifts)
end

View the entire Elixir script for this task on GitHub.


Here’s all my solutions in GitHub: https://github.com/packy/perlweeklychallenge-club/tree/challenge-402-packy-anderson/challenge-402/packy-anderson

Leave a Reply