Monday, November 30, 2026

TWC402

Challenge Link

Task1

We convert to hex, then change 1 to I and 0 to O, then check if there are any digits, if so empty string, otherwise the string itself is returned:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 4;

sub letters_only_hex{
  my $s = sprintf("%X",shift) =~ tr/10/IO/r;
  $s =~ /\d/ ? '' : $s
}

is letters_only_hex('16'),'IO','Example 1';
is letters_only_hex('10'),'A','Example 2';
is letters_only_hex('2748'),'ABC','Example 3';
is letters_only_hex('4098'),'','Example 4';

Task2

We make circular rotations according to the given directions:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 6;

sub circular_string_rotations{
  my ($str,$dirs) = @_;
  my $n = length $str;
  my $shift = 0;
  $shift += $_->[0] ? -$_->[1] : $_->[1] for @$dirs;
  $shift %= $n;
  substr($str,$shift) . substr($str,0,$shift)
}

is circular_string_rotations('hello',[[1,3],[0,3]]),
  'hello','Example 1';
is circular_string_rotations('abcd',
			     [[1,6]]),'cdab','Example 2';
is circular_string_rotations('coding',
			     [[0,4],[1,2]]),'dingco','Example 3';
is circular_string_rotations('planet',
			     [[0,11],[1,4],[0,2]]),
  'netpla','Example 4';
is circular_string_rotations('z',[[0,5],[1,9]]),'z','Example 5';
is circular_string_rotations('jubilee',
			     [[0,12],[1,3],[0,9]]),
  'leejubi','Example 6';

No comments:

Post a Comment