Showing posts with label raku. Show all posts
Showing posts with label raku. Show all posts

Sunday, November 22, 2026

TWC401

Challenge Link

Task1

We parse the digits and find the result:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub gcd{
  my ($a,$b) = map{abs} @_;
  ($a,$b) = ($b,$a % $b) while $b;
  $a
}

sub fraction_addition_subtraction{
  my ($expr) = @_;
  my ($num,$den) = (0,1);
  while($expr =~ m{([+-]?\d+)/(\d+)}g){
    my ($n,$d) = ($1,$2);
    $num = $num * $d + $n * $den;
    $den *= $d;
    my $g = gcd($num,$den);
    ($num,$den) = ($num / $g,$den / $g) if $g > 1
  }
  "$num/$den"
}

is fraction_addition_subtraction('1/2+3/2'),'2/1','Example 1';
is fraction_addition_subtraction('-5/2-3/2'),'-4/1','Example 2';
is fraction_addition_subtraction('5/3-5/3'),'0/1','Example 3';
is fraction_addition_subtraction('10/10-1/10+2/5'),'13/10','Example 4';
is fraction_addition_subtraction('1/6+1/6+1/6'),'1/2','Example 5';

Task2

We reconstruct the digits using a mapping of steps:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

my @STEPS = (
  [0,'z','zero'],
  [2,'w','two'],
  [4,'u','four'],
  [6,'x','six'],
  [8,'g','eight'],
  [3,'h','three'],
  [5,'f','five'],
  [7,'s','seven'],
  [1,'o','one'],
  [9,'i','nine'],
);

sub reconstruct_digits{
  my ($str) = @_;
  my %count;
  $count{$_}++ for split '',$str;

  my @times = (0) x 10;
  foreach my $step(@STEPS){
    my ($digit,$key,$word) = @$step;
    my $n = $count{$key} or next;
    $times[$digit] = $n;
    $count{$_} -= $n for split '',$word;
  }
  join '',map{$_ x $times[$_]} 0..9
}

is reconstruct_digits('zroezerotwotwotwo'),'00222','Example 1';
is reconstruct_digits('sveeneinght'),'78','Example 2';
is reconstruct_digits('onenineninefive'),'1599','Example 3';
is reconstruct_digits('zeroonetwothreeeightfivesixsevenninefour'),
  '0123456789','Example 4';
is reconstruct_digits('ninenineninenine'),'9999','Example 5';

Tuesday, November 17, 2026

TWC400

Challenge Link

Task1

We find the biggest jump between numbers without repeating digits:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(reduce max);
use Test::More tests => 5;

sub largest_interval{
  my @nums = grep{!/(.).*\1/} 1..$_[0];
  my $jump = 0;
  reduce{$jump = max($jump,$b - $a); $b} @nums;
  $jump
}

is largest_interval(20),2,'Example 1';
is largest_interval(110),4,'Example 2';
is largest_interval(500),11,'Example 3';
is largest_interval(2026),105,'Example 4';
is largest_interval(10000),105,'Example 5';

Task2

We find the minimum number of mutations required to mutate from start to end gene:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub minimum_genetic_mutation{
  my ($start,$end,$bank) = @_;
  return 0 if $start eq $end;

  my %valid = map{$_ => 1} @$bank;
  return -1 unless $valid{$end};

  my %seen = ($start => 1);
  my @queue = ([$start,0]);

  while(@queue){
    my ($gene,$steps) = @{shift @queue};
    foreach my $i(0..length($gene)-1){
      foreach my $c(qw(A C G T)){
	next if substr($gene,$i,1) eq $c;

	my $next = $gene;
	substr($next,$i,1) = $c;
	
	next unless $valid{$next};
	next if $seen{$next}++;

	return $steps+1 if $next eq $end;
	push @queue,[$next,$steps+1]
      }
    }
  }
  -1
}

is minimum_genetic_mutation('AACCGGTT',
			    'AACCGGTA',
			    ['AACCGCTA','AAACGGTA']),-1,'Example 1';
is minimum_genetic_mutation('AACCGGTT',
			    'AACCGGAA',
			    ['AACCGGTA','AACCGGAA','AACCGCTA',
			     'AACCCTAA','AACCGTAA']),2,'Example 2';
is minimum_genetic_mutation('AAAAAAAA',
			    'AAAAACCC',
			    ['CAAAAAAA',
			     'CCAAAAAA','AAAAAAAC']),-1,'Example 3';
is minimum_genetic_mutation('GAAAAAAA',
			    'GCCCCCCC',
			    ['GCAAAAAA','GCCAAAAA','GCCCAAAA',
			     'GCCCCAAA','GCCCCCAA',
			     'GCCCCCCA','GCCCCCCC']),7,'Example 4';
is minimum_genetic_mutation('AACCGGTT',
			    'AACCGGTT',['AACCGGTA']),0,'Example 5';

Tuesday, November 10, 2026

TWC399

Challenge Link

Task1

We find the longest repeating character:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub longest_repeating_character{
  my ($s,$k) = @_;
  my ($left,$max_count,%count) = (0,0);
  my $n = length $s;
  foreach my $right(0..$n-1){
    my $c = substr($s,$right,1);
    $count{$c}++;
    $max_count = $count{$c} if $count{$c} > $max_count;
    if(($right - $left + 1) - $max_count > $k){
      $count{substr($s,$left,1)}--;
      $left++
    }
  }
  $n - $left
}

is longest_repeating_character('AAAAA',2),5,'Example 1';
is longest_repeating_character('ABCDE',4),5,'Example 2';
is longest_repeating_character('AAABBBBAA',1),5,'Example 3';
is longest_repeating_character('ABACADA',2),5,'Example 4';
is longest_repeating_character('BAAABAAAA',1),8,'Example 5';

Task2

We find the longest absolute path:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub longest_absolute_path{
  my ($fs) = @_;
  my @lines = grep{length} split /\n/,$fs;
  my @depth = map{/^(\t*)/; length $1} @lines;
  my ($best,@len) = (0);
  
  foreach my $i(0..$#lines){
    my $d = $depth[$i];
    my $name = substr($lines[$i],$d);
    $len[$d] = ($d > 0 ? $len[$d-1]+1 : 0) + length $name;
    my $is_dir = ($i < $#lines && $depth[$i+1] > $d);
    if(!$is_dir && index($name,'.') >= 0){
      $best = $len[$d] if $len[$d] > $best
    }
  }
  $best
}

is longest_absolute_path("dir\n\tsubdir1\n\t\tsubsubdir1\n\tsubdir2"),0,'Example 1';
is longest_absolute_path("file1.txt\nfile2.ext\na.png"),9,'Example 2';
is longest_absolute_path("my documents\n\tproject v1.0\n\t\tnotes v1.txt\n\timage.png"),38,'Example 3';
is longest_absolute_path("root\n\ta\n\t\tb\n\t\t\tc.txt\n\td\n\t\te.txt"),14,'Example 4';
is longest_absolute_path("a\n\tb\n\t\tc\n\t\t\td\n\t\t\t\te.txt\n\tvery_long_directory_name\n\t\tf.txt"),32,'Example 5';

Tuesday, November 3, 2026

TWC398

Challenge Link

Task1

We filter even numbers and those numbers which are divisible by 3, then find its average:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0);
use Test::More tests => 5;

sub divisible_average{
  my @arr = grep {$_ % 2 == 0 && $_ % 3 == 0} @{$_[0]};
  return 0 unless @arr;
  int((sum0 @arr) / @arr)
}

is divisible_average([18,5,7,11]),18,'Example 1';
is divisible_average([6,12,18,24,30,40]),18,'Example 2';
is divisible_average([3,9,15,21,27]),0,'Example 3';
is divisible_average([6,12,14,20]),9,'Example 4';
is divisible_average([6,6,6,12,12]),8,'Example 5';

Task2

We find the difference between letters of strings, and find the odd one:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub string_difference{
  my ($words) = @_;
  my (@keys,%h);
  foreach my $w(@$words){
    my @ord = map {ord($_) - ord('a')} split '',$w;
    my $key = join ',',map{$ord[$_+1] - $ord[$_]} 0..$#ord-1;
    push @keys,$key;
    $h{$key}++
  }
  foreach my $i(0..$#$words){
    return $words->[$i] if $h{$keys[$i]} == 1;
  }
  return -1
}

is string_difference(['ab','bc','cd','zy']),'zy','Example 1';
is string_difference(['cba','fed','azy']),'azy','Example 2';
is string_difference(['pop','ada','beb','cfc']),'pop','Example 3';
is string_difference(['aaaa','zzzz','mmmm','aaba']),'aaba','Example 4';
is string_difference(['aceg','bdfh','cegi','azbz']),'azbz','Example 5';

Monday, October 26, 2026

TWC397

Challenge Link

Task1

We find the smallest number greater than average of the array:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;
use List::Util qw(max sum0);

sub absent_smallest_positive{
  my ($arr) = @_;
  my ($sum,%h);
  foreach(@$arr){
    $h{$_} = 1;
    $sum += $_;
  }
  my $ret = max(1,int($sum / @$arr) + 1);
  $ret++ while(exists $h{$ret});
  $ret
}

is absent_smallest_positive([1,2,4,5,6]),7,'Example 1';
is absent_smallest_positive([-5,-2,-1,3]),1,'Example 2';
is absent_smallest_positive([1..3]),4,'Example 3';
is absent_smallest_positive([2,3,7,8]),6,'Example 4';
is absent_smallest_positive([1,1,1,10]),4,'Example 5';

Task2

We first sort by binary representation, then by numbers themselves:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub binary_reflection{
  my $rb = sub{oct('0b' . reverse sprintf("%b",shift))};
  [sort{$rb->($a) <=> $rb->($b) || $a <=> $b} @{$_[0]}]
}

is_deeply binary_reflection([3,6,12]),[3,6,12],'Example 1';
is_deeply binary_reflection([1,2,4,8]),[1,2,4,8],'Example 2';
is_deeply binary_reflection([7,8,9,10]),[8,10,7,9],'Example 3';
is_deeply binary_reflection([5,9,15,17]),[5,9,15,17],'Example 4';
is_deeply binary_reflection([11,13,14,19]),[14,13,11,19],'Example 5';

Monday, October 19, 2026

TWC396

Challenge Link

Task1

We sort the elements according to order array:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub finishing_order{
  my %h;
  $h{$_} = 1 foreach @{$_[1]};
  [grep {$h{$_}} @{$_[0]}];
}

is_deeply finishing_order([3,1,4,2,5],[1,2,4]),[1,4,2],'Example 1';
is_deeply finishing_order([5,4,3,2,1],[1,3,5]),[5,3,1],'Example 2';
is_deeply finishing_order([2,4,1,3],[1,2,3,4]),[2,4,1,3],'Example 3';
is_deeply finishing_order([4,1,3,2],[3]),[3],'Example 4';
is_deeply finishing_order([1,3,2,6,5,4],[1,2,3]),[1,3,2],'Example 5';

Task2

We check if array is trionic:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub trionic_array{
  my ($arr) = @_;
  my ($p,$n) = (0,scalar @$arr);
  $p++ while($p < $n - 2 && $arr->[$p] < $arr->[$p+1]);
  return '' if $p == 0;
  my $q = $p;
  $q++ while($q < $n-1 && $arr->[$q] > $arr->[$q+1]);
  return '' if $q == $p || $q == $n-1;
  $q++ while($q < $n-1 && $arr->[$q] < $arr->[$q+1]);
  $q == $n-1
}

is trionic_array([1,3,5,4,2,6,8]),1,'Example 1';
is trionic_array([1,4,4,2,1,3,5]),'','Example 2';
is trionic_array([2,10,3,1,9]),1,'Example 3';
is trionic_array([1,2,3,4,3,2,1]),'','Example 4';
is trionic_array([1,3,6,4,2,7,8,4]),'','Example 5';

Sunday, October 11, 2026

TWC395

Challenge Link

Task1

We parse complex numbers and apply the given formula:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub parse_complex{
  my ($s) = @_;
  if ($s =~ /^\s*(-?\d+)\s*\+\s*\(?\s*(-?\d+)\s*\)?\s*i\s*$/){
    return ($1, $2);
  }
  die "Invalid complex number: '$s'\n"
}

sub format_complex{
  my ($re,$im) = @_;
  my $str = $im < 0 ? "($im)" : "$im";
  "$re+${str}i"
}

sub complex_number{
  my ($n1,$n2) = @_;
  my ($a,$b) = parse_complex($n1);
  my ($c,$d) = parse_complex($n2);
  my $real = $a * $c - $b * $d;
  my $imag = $a * $d + $b * $c;
  format_complex($real,$imag)
}

is complex_number('1+1i','1+1i'),'0+2i','Example 1';
is complex_number('1+(-1)i','1+(-1)i'),'0+(-2)i','Example 2';
is complex_number('0+3i','0+4i'),'-12+0i','Example 3';
is complex_number('3+4i','3+(-4)i'),'25+0i','Example 4';
is complex_number('50+(-20)i','-10+30i'),'100+1700i','Example 5';

done_testing();

Task2

We use backtracking to find all the solutions:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub word_squares{
  my ($words) = @_;
  return [] unless @$words;

  my ($n,@res,%used) = length $words->[0];
  
  my $solve;
  $solve = sub{
    my $k = @res;
    return 1 if $k == $n;
    my $prefix = join '',map{substr($res[$_],$k,1)} 0..$k-1;
    
    foreach my $i(0..$#$words){
      next if $used{$i};
      next unless substr($words->[$i],0,$k) eq $prefix;
      $used{$i} = 1;
      push @res,$words->[$i];
      return 1 if $solve->();
      pop @res;
      delete $used{$i}
    }
    0
  };

  my $found = $solve->();
  undef $solve;
  $found ? \@res : [];
}

is_deeply word_squares(['MA','AM','MY','ME']),['MA','AM'],'Example 1';

is_deeply word_squares(['SUN','USE','NET','SEE','TEN']),
  ['SUN','USE','NET'],'Example 2';

is_deeply word_squares(['BOAT','TEAL','AREA','TSAR','OGRE']),
  ['BOAT','OGRE','AREA','TEAL'],'Example 3';

is_deeply word_squares(['CARD','AREA','REAR','DART']),
  ['CARD','AREA','REAR','DART'],'Example 4';

is_deeply word_squares(['HEART','TREND','EMBER','RESIN','ABUSE']),
  ['HEART','EMBER','ABUSE','RESIN','TREND'],'Example 5';

done_testing();

Tuesday, October 6, 2026

TWC394

Challenge Link

Task1

We find the minimum number of required swaps to make alternating string:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(min);
use Test::More tests => 5;

sub alternate_case{
  my ($s) = @_;
  my @upper;
  push @upper,$-[0] while($s =~ /[A-Z]/g);
  my $cost = sub {
    my ($start) = @_;
    my $total = 0;
    foreach my $i(0..$#upper) {
      my $target = $start + 2 * $i;
      $total += abs($upper[$i] - $target)
    }
    return $total
  };
  min($cost->(0),$cost->(1))
}

is alternate_case('aAbB'),0,'Example 1';
is alternate_case('AAbb'),1,'Example 2';
is alternate_case('AAAbbb'),3,'Example 3';
is alternate_case('aABb'),1,'Example 4';
is alternate_case('bBBAaa'),2,'Example 5';

done_testing();

Task2

We find the longest substring common to all elements of the array and which is alternating between consonants and vowels:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub iv {return $_[0] =~ /[aeiou]/i ? 1 : 0}

sub alternating_vowels_consonants{
  my ($strs) = @_;
  my ($src,@others) = sort {length $a <=> length $b} @$strs;
  my $max = 0;
  my (@best,%seen);
  my $n = length $src;

  foreach my $i(0..$n-1){
    foreach my $j($i..$n-1){
      last if $j > $i &&
	iv(substr($src,$j,1)) 
	== iv(substr($src,$j-1,1));
      my $len = $j - $i + 1;
      next if $len < $max;

      my $sub = substr($src,$i,$len);
      next if grep {index(lc $_,lc $sub) < 0} @others;

      if($len > $max) {
	$max = $len;
	@best = ();
	%seen = ();
      }
      push @best,$sub unless $seen{$sub}++;
    }
  }
  \@best
}

is_deeply alternating_vowels_consonants(
  ['relocate','delocate','allocate']),['locate'],'Example 1';
is_deeply alternating_vowels_consonants(
  ['apple','banana','cherry']),[],'Example 2';
is_deeply alternating_vowels_consonants(
  ['navigate','cavity','gravity']),['avi'],'Example 3';
is_deeply alternating_vowels_consonants(
  ['pedalgia','pedalboard','pedantic']),['peda'],'Example 4';
is_deeply alternating_vowels_consonants(
  ['schoolmaster','schoolhouse','schooling']),['ho','ol'],'Example 5';

done_testing();

Monday, September 28, 2026

TWC393

Challenge Link

Task1

Solving this using Euclid's formula:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;
use ntheory qw(gcd);

sub pythagoras_multiplied{
  my ($n) = @_;
  my $count = 0;
  for(my $m = 2; $m * $m + 1 <= $n; $m++){
    for(my $k = 1; $k < $m; $k++){
      next if (($m - $k) % 2 == 0) || gcd($m,$k) != 1;
      my $c = $m * $m + $k * $k;
      last if $c > $n && $k == 1;
      next if $c > $n;
      $count += 2 * int($n / $c)
    }
  }
  $count
}

is pythagoras_multiplied(20),12,'Example 1';
is pythagoras_multiplied(7),2,'Example 2';
is pythagoras_multiplied(1),0,'Example 3';
is pythagoras_multiplied(15),8,'Example 4';
is pythagoras_multiplied(30),22,'Example 5';

done_testing();

Task2

We find the sum of all ascii values in the string and check for primality:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0);
use ntheory qw(is_prime);
use Test::More tests => 5;

sub prime_step{
  my $sum = sum0 map{ord} split '',$_[0];
  my $d = 0;
  while(1){
    return $d if is_prime($sum - $d) || is_prime($sum + $d);
    $d++
  }
}

is prime_step('hello'),9,'Example 1';
is prime_step('football'),2,'Example 2';
is prime_step('a'),0,'Example 3';
is prime_step('challenge'),2,'Example 4';
is prime_step('perl'),2,'Example 5';

done_testing();

Monday, September 21, 2026

TWC392

Challenge Link

Task1

We keep on adding characters till we find the palindrome:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub convert_palindrome{
  my $r = reverse $_[0];
  my $n = length $_[0];
  foreach my $i(0..$n) {
    if(substr($_[0],0,$n-$i) eq substr($r,$i)) {
      return substr($r,0,$i) . $_[0]
    }
  }
}

is convert_palindrome('pinnipeds'),'sdepinnipeds','example 1';
is convert_palindrome('abcd'),'dcbabcd','example 2';
is convert_palindrome('bananas'),'sananabananas','example 3';
is convert_palindrome('dissident'),'tnedissident','example 4';
is convert_palindrome('cailliachs'),'shcailliachs','example 5';

done_testing();

Task2

We count the words that don't have any common letters and calculate the product of their lengths:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(any max);
use Test::More tests => 5;

sub common_letters{
  my ($s1,$s2) = @_;
  my %h = map{$_ => 1} split '',$s1;
  any {$h{$_}} split '',$s2
}

sub words_length_product{
  my ($words) = @_;
  my $best = 0;
  foreach my $i(0..$#$words-1) {
    foreach my $j($i+1..$#$words) {
      my ($w1,$w2) = @{$words}[$i,$j];
      next if common_letters($w1,$w2);
      $best = max($best,length($w1) * length($w2))
    }
  }
  $best
}

is words_length_product(["a","ab","abc","d","de","def"]),9,
  'Example 1';
is words_length_product(["a","aa","aaa","aaaa"]),0,'Example 2';
is words_length_product(["meet","app","code","sky","bold"]),16,
  'Example 3';
is words_length_product(["a","ab","abc","abcd","efghi"]),20,
  'Example 4';
is words_length_product(["xyz","w","abcdefg","hij"]),21,'Example 5';

done_testing();

Tuesday, September 15, 2026

TWC391

Challenge Link

Task1

We merge and sort the arrays and then find the median:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub array_median{
  my ($arr1,$arr2) = @_;
  my @merged = sort {$a <=> $b} (@$arr1,@$arr2);
  return 0.0 if @merged == 0;

  if(@merged % 2 == 1) {
    return $merged[int(@merged / 2)] + 0.0
  } else {
    my $left_middle = @merged / 2 - 1;
    return ($merged[$left_middle] + $merged[$left_middle+1]) / 2
  }
}

is array_median([2],[4]),3.0,'Example 1';
is array_median([1..3],[7..10]),7.0,'Example 2';
is array_median([],[10,20,30,40]),25.0,'Example 3';
is array_median([100],[1..7]),4.5,'Example 4';
is array_median([1,2,2],[2,2,3]),2.0,'Example 5';

done_testing();

Task2

We arrange the boxes so that they can fit in each other and count how many can:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub arrange_box{
  my ($boxes) = @_;
  my @sorted = sort {$a->[0] <=> $b->[0] ||
		       $b->[1] <=> $a->[1]} @$boxes;
  
  my @heights = map {$_->[1]} @sorted;
  my $n = @heights;
  return 0 if $n == 0;
  
  my @dp = (1) x $n;
  my $max = 1;
  foreach my $i(0..$n-1) {
    foreach my $j(0..$i-1) {
      if($sorted[$j][0] < $sorted[$i][0] &&
	 $sorted[$j][1] < $sorted[$i][1] &&
	 $dp[$j] + 1 > $dp[$i]) {
	$dp[$i] = $dp[$j]+1;
	$max = $dp[$i] if $dp[$i] > $max
      }
    }
  }
  $max
}

is arrange_box([[1,3],[3,5],[6,8],[2,4]]),4,'Example 1';
is arrange_box([[4,5],[4,6],[6,7],[2,3],[4,3]]),3,'Example 2';
is arrange_box([[5,5],[5,5],[5,5]]),1,'Example 3';
is arrange_box([[2,100],[3,200],[4,300],[5,50],[5,400]]),
  4,'Example 4';
is arrange_box([[10,20],[15,10],[20,30],[12,18],[16,25]]),
  3,'Example 5';

done_testing();

Monday, September 7, 2026

TWC390

Challenge Link

Task1

We repeat each given character n times according to the given rules:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub decode_string{
  my (@s1,@s2);
  my $num = 0;
  my $res = '';
  foreach my $c(split '',$_[0]){
    if($c =~ /\d/) {
      $num = $num * 10 + $c - '0'
    } elsif($c eq '[') {
      push @s1,$num;
      push @s2,$res;
      $num = 0;
      $res = ''
    } elsif($c eq ']') {
      my $t = '';
      for(my ($i,$n) = (0,pop @s1); $i < $n; ++$i) {
	$t .= $res
      }
      $res = (pop @s2) . $t
    } else {
      $res .= $c
    }
  }
  $res
}

is decode_string('2[3[a]]'),'aaaaaa','Example 1';
is decode_string('10[a]'),'aaaaaaaaaa','Example 2';
is decode_string('a2[b]c3[d]e'),'abbcddde','Example 3';
is decode_string('2[a2[b]c]'),'abbcabbc','Example 4';
is decode_string('1[a]2[b3[c]]'),'abcccbccc','Example 5';

done_testing();

Task2

We reorder characters until we find the smallest string:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 7;

sub order_characters{
  my ($s,$k) = @_;
  if ($k == 1) {
    my $n = length($s);
    my $doubled = $s . $s;
    my $best = substr($doubled,0,$n);
    foreach my $i(1..$n-1) {
      my $candidate = substr($doubled,$i,$n);
      $best = $candidate if $candidate lt $best
    }
    return $best
  } else {
    return join('',sort split '',$s)
  }
}

is order_characters('dbca',1),'adbc','Example 1';
is order_characters('geeks',2),'eegks','Example 2';
is order_characters('cbaed',3),'abcde','Example 3';
is order_characters('fedcba',4),'abcdef','Example 4';
is order_characters('perl',1),'erlp','Example 5';
is order_characters('oloolooo',1),'looloooo','Example 6';
is order_characters('oloooolo',1),'looloooo','Example 7';

done_testing();

Tuesday, September 1, 2026

TWC389

Challenge Link

Task1

We reorder notes according to the permutation array:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub reorder_notes{
  my ($composer,$notes,$perm) = @{$_[0]};
  my @reordered;
  $reordered[$perm->[$_]-1] = $notes->[$_] foreach 0..$#$perm;
  uc($composer) . ' => ' . join ' ',@reordered
}

is reorder_notes(['Bach',['C','D','E','F#','G','A','B'],
		  [7,1,6,2,5,3,4]]),
  'BACH => D F# A B G E C','Example 1';
is reorder_notes(['Beethoven',
		  ['C','D','F#','G','Ab'],
		  [1, 3, 5, 2, 4]]),
  'BEETHOVEN => C G D Ab F#','Example 2';
is reorder_notes(['Brahms',
		  ['C','Db','Eb','F','G','Ab','Bb','C','D'],
		  [9,3,7,1,8,5,2,6,4]]),
  'BRAHMS => F Bb Db D Ab C Eb G C','Example 3';
is reorder_notes(['Bruckner',
		  ['G','F#','Bb','C','D','Eb','F'],
		  [4,7,2,6,1,5,3]]),
  'BRUCKNER => D Bb F G Eb C F#','Example 4';
is reorder_notes(['Berg',
		  ['C#'],
		  [1]]),'BERG => C#','Example 5';

done_testing();

Task2

We find the length of longest zig-zag subarray:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub zig_zag_subarray{
  my ($arr) = @_;
  return 1 if @{$arr} == 1;
  return 2 if @{$arr} == 2 && $arr->[0] != $arr->[1];
  my ($max,$from,$to) = (1,0,0);
  while($to++ < $#$arr){
    $from = $to, next if $arr->[$to-1] == $arr->[$to];
    $from = $to-1, next if $to - $from > 1
      && ($arr->[$to] <=> $arr->[$to-1]) 
      == ($arr->[$to-1] <=> $arr->[$to-2]);
    my $curr = 1 + $to - $from;
    $max = $curr if $curr > $max
  }
  $max
}

is zig_zag_subarray([9,4,2,10,7,8,8,1,9]),5,'Example 1';
is zig_zag_subarray([1,7,4,9,2,5]),6,'Example 2';
is zig_zag_subarray([1..5]),2,'Example 3';
is zig_zag_subarray([4,4,4]),1,'Example 4';
is zig_zag_subarray([10,20,15,12,18]),3,'Example 5';

done_testing();

Saturday, August 29, 2026

TWC388

Challenge Link

Task1

We find the dyck words using a stack:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub dyck_words{
  my ($n) = @_;
  return [''] if $n == 0;
  my @res;
  my @stack = [0,0,''];
  while(@stack){
    my $state = pop @stack;
    my ($o,$c,$curr) = @$state;
    if($o == $n && $c == $n) {
      push @res,$curr;
      next
    }
    push @stack,[$o+1,$c,$curr . 'U'] if $o < $n;
    push @stack,[$o,$c+1,$curr . 'D'] if $c < $n && $o > $c;
  }
  @res = sort @res;
  \@res
}

is_deeply dyck_words(1),['UD'],'Example 1';
is_deeply dyck_words(2),['UDUD','UUDD'],'Example 2';
is_deeply dyck_words(3),['UDUDUD','UDUUDD','UUDDUD','UUDUDD',
			 'UUUDDD'],'Example 3';
is_deeply dyck_words(0),[''],'Example 4';
is_deeply dyck_words(4),['UDUDUDUD','UDUDUUDD','UDUUDDUD',
			 'UDUUDUDD','UDUUUDDD','UUDDUDUD',
			 'UUDDUUDD','UUDUDDUD','UUDUDUDD',
			 'UUDUUDDD','UUUDDDUD','UUUDDUDD',
			 'UUUDUDDD','UUUUDDDD'],'Example 5';

done_testing();

Task2

We find the number of valid gifts:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;
use Memoize;

memoize qw(derange);
sub derange{
  my ($n) = @_;
  return 1 if $n == 0;
  $n * derange($n-1) + ($n % 2 == 0 ? 1 : -1)
}

is derange(1),0,'Example 1';
is derange(2),1,'Example 2';
is derange(3),2,'Example 3';
is derange(4),9,'Example 4';
is derange(5),44,'Example 5';

done_testing();

Monday, August 17, 2026

TWC387

Challenge Link

Task1

We replace "01" with "10" until none exists:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub rearrange_binary_string{
  my ($s) = @_;
  my $c = 0;
  $c++ while $s =~ s/01/10/g;
  $c
}

is rearrange_binary_string('111000'),0,'Example 1';
is rearrange_binary_string('00011'),4,'Example 2';
is rearrange_binary_string('01011'),3,'Example 3';
is rearrange_binary_string('010101'),3,'Example 4';
is rearrange_binary_string('00001'),4,'Example 5';

done_testing();

Task2

We follow the given instructions:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub rational_numbers{
  my ($s) = @_;
  my %h;
  $s =~ s/([A-Z][a-z]?)(\d+)/$1 x $2/gex;
  1 while $s =~ s/\(([^()]+)\) (\d+)/$1 x $2/gex;
  $h{$_}++ foreach $s =~ /[A-Z][a-z]?/gx;
  join '',map {$_ . ($h{$_} > 1 ? $h{$_} : '')} sort keys %h
}

is rational_numbers('((N2O)3(H2O)2)2'),'H8N12O10','Example 1';
is rational_numbers('Mg3(PO4)2'),'Mg3O8P2','Example 2';
is rational_numbers('(((H)2)3)4'),'H24','Example 3';
is rational_numbers('NaCl3(O2(S10)2)2Mg'),'Cl3MgNaO4S40','Example 4';
is rational_numbers('Z2Y3(X2W)2'),'W2X4Y3Z2','Example 5';

done_testing();

Friday, August 14, 2026

TWC386

Challenge Link

Task1

We do the conversion according to the given base:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

my $i = 0;
my %val = map {$_ => $i++} 0..9,'A'..'Z','a'..'z','+','/';

sub reverse_base{
  my ($num,$base) = @_;
  my $res = 0;
  for(my $n = 1; length $num; $n *= $base) {
    $res += $n * $val{substr $num,-1,1,''}
  }
  $res
}

is reverse_base('101010',2),42,'Example 1';
is reverse_base('EEADEE',16),15642094,'Example 2';
is reverse_base('755',8),493,'Example 3';
is reverse_base('1BRJB',36),2228519,'Example 4';
is reverse_base('7MyqL',64),123456789,'Example 5';

done_testing();

Task2

We find if the two rationals are equal:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub rational_numbers{
  my ($rat1,$rat2) = @_;
  my @rats;
  foreach my $r($rat1,$rat2) {
    $r .= '.' if -1 == index $r,'.';
    $r =~ /([-+]?\d+)\.(\d*)(?:\((\d+)\))?$/;
    my ($int,$prefix,$repeated) = @{^CAPTURE};
    $repeated //= '';
    $repeated = $1 if $repeated =~ /^(.+?)\1+$/;
    while(length $repeated &&
	  substr($repeated,-1,1) eq substr $prefix,-1,1) {
      substr $repeated,0,0,substr $prefix,-1,1,'';
      substr $repeated,-1,1,'';
      if('9' eq $repeated) {
	$repeated = '';
	if(length $prefix) {
	  if($prefix =~ /9$/) {
	    $prefix =~ s/9+$//;
	    if(length $prefix) {
	      ++$prefix
	    } else {
	      ++$int
	    }
	  } else {
	    ++$prefix
	  }
	} else {
	  ++$int
	}
	last
      }
    }
    $repeated = '' if '0' eq $repeated;
    $prefix = '' if '' eq $repeated && '0' eq $prefix;
    push @rats,"$int|$prefix|$repeated"
  }
  return $rats[0] eq $rats[1]
}

is rational_numbers('0.(12)','0.(121)'),'','Example 1';
is rational_numbers('0.1(23)','0.12(32)'),1, 'Example 2';
is rational_numbers('0.1(234)','0.12(342)'),1,'Example 3';
is rational_numbers('12.99(99)','13.'),1,'Example 4';
is rational_numbers('0.(123)','0.1(231)'),1,'Example 5';

done_testing();

Friday, August 7, 2026

TWC385

Challenge Link

Task1

We look for words uncommon to both strings:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub uncommon_words{
  my %h;
  $h{$_}++ foreach split /\s+/,"$_[0] $_[1]";
  grep {$h{$_} == 1} keys %h
}

show uncommon_words('apple banana apple','banana orange');
show uncommon_words('cat dog','bird fish');
show uncommon_words('the quick brown fox','the quick');
show uncommon_words('hello','hello');
show uncommon_words('blue blue red','red green green yellow');

Task2

We remove outermost parentheses:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub outermost_parentheses{
  my %h = ('(' => 1, ')' => 0);
  my $depth = 0;
  join '',
    map $h{$_} == ($depth += $_ eq '(' ? 1 : -1) ? '' : $_,
    split '',$_[0]
}

is outermost_parentheses('()()()'),'','Example 1';
is outermost_parentheses('(((())))'),'((()))','Example 2';
is outermost_parentheses('(()())(())'),'()()()','Example 3';
is outermost_parentheses('()((()))()'),'(())','Example 4';
is outermost_parentheses('(()(()))(()())'),'()(())()()','Example 5';

done_testing();

Monday, July 27, 2026

TWC384

Challenge Link

Task1

Simple base conversion:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub base_n{
  my ($num,$base) = @_;
  my @chars = ('0'..'9','A'..'Z','a'..'z','+','/');
  my @digits;
  if($num == 0){
    @digits = (0);
  } else {
    while($num > 0){
      unshift @digits,$num % $base;
      $num = int($num / $base)
    }
  }
  join '',map{$chars[$_]} @digits
}

is base_n(42,2),'101010','Example 1';
is base_n(15642094,16),'EEADEE','Example 2';
is base_n(493,8),'755','Example 3';
is base_n(2228519,36),'1BRJB','Example 4';
is base_n(123456789,64),'7MyqL','Example 5';

done_testing();

Task2

We enumerate each candidate and find ones which have equal length and same number of zeros and ones:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub special_binary_substrings {
  my ($b) = @_;
  my @m;
  foreach my $pos(0..length($b)-1){
    foreach my $len(2..length($b) - $pos) {
      my $sub = substr($b,$pos,$len);
      next unless $sub =~ /^(0+1+|1+0+)$/;
      my ($f,$s) = $sub =~ /^(0+)(1+)$/ 
	? ($1,$2) 
	: $sub =~ /^(1+)(0+)$/;
      push @m, $sub if length($f) == length($s);
    }
  }
  \@m;
}

is_deeply special_binary_substrings('0101'),
  ['01','10','01'],'Example 1';
is_deeply special_binary_substrings('000111'),
  ['000111','0011','01'],'Example 2';
is_deeply special_binary_substrings('000011'),
  ['0011','01'],'Example 3';
is_deeply special_binary_substrings('10011100'),
  ['10','0011','01','1100','10'],'Example 4';
is_deeply special_binary_substrings('00000'),[],'Example 5';

done_testing();

Tuesday, July 21, 2026

TWC383

Challenge Link

Task1

We check if elements belong to the same synonym group:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub similar_list{
  return 0 unless @{$_[0]} == @{$_[1]};
 OUTER:
  foreach my $i(0..$#{$_[0]}){
    next OUTER if $_[0]->[$i] eq $_[1]->[$i];
    foreach my $sub(@{$_[2]}){
      next OUTER if in($_[0]->[$i],$sub) &&
	in($_[1]->[$i],$sub)
      }
    return 0
  }
  1
}

sub in{
  my ($e,$l) = @_;
  grep {$_ eq $e} @$l
}

is similar_list(['great','acting'],
		['fine','drama'],
		[['great','fine'],
		 ['acting','drama']]),1,'Example 1';
is similar_list(['apple','pie'],
		['banana','pie'],
		[['apple','peach'],
		 ['peach','banana']]),0,'Example 2';
is similar_list(['perl4','python'],
		['raku','python'],
		[['perl4','perl5','raku']]),1,'Example 3';
is similar_list(['enjoy','challenge'],
		['love', 'weekly', 'challenge'],
		[['enjoy','love']]),0,'Example 4';
is similar_list(['fast','car'],
		['quick','vehicle'],
		[['quick','fast'],['vehicle','car']]),1,'Example 5';
done_testing();

Task2

We make the colors web safe according to the given rules:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub nearest_rgb{
  my @web_safe = (0,51,102,153,204,255);
  my ($r,$g,$b) = map hex,$_[0] =~ /#(..)(..)(..)/;
  my $safe = '#';
  foreach my $c($r,$g,$b) {
    my $best = 0;
    foreach my $s(@web_safe){
      $best = $s if abs($c - $s) < abs($best - $c)
    }
    $safe .= sprintf '%02X',$best
  }
  $safe
}

is nearest_rgb('#F4B2D1'),'#FF99CC','Example 1';
is nearest_rgb('#15E6E5'),'#00FFCC','Example 2';
is nearest_rgb('#191A65'),'#003366','Example 3';
is nearest_rgb('#2D5A1B'),'#336633','Example 4';
is nearest_rgb('#00FF66'),'#00FF66','Example 5';

done_testing();

Monday, July 6, 2026

TWC381

Challenge Link

Task1

We check if every row and column contains digits from 1 to n:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub same_row_column{
  my ($m) = @_;
  my $n = @$m;

  foreach my $row (@$m){
    my %h;
    foreach my $num(@$row){
      return 0 if ($num < 1 || $num > $n || $h{$num}++);
    }
  }
  
  foreach my $col(0..$n-1){
    my %h;
    foreach my $row(@$m){
      my $num = $row->[$col];
      return 0 if ($num < 1 || $num > $n || $h{$num}++);
    }
  }
  1
}

is same_row_column([[1,2,3,4],[2,3,4,1],
		    [3,4,1,2],[4,1,2,3]]),1,'Example 1';
is same_row_column([[1]]),1,'Example 2';
is same_row_column([[1,2,5],[5,1,2],[2,5,1]]),0,'Example 3';
is same_row_column([[1,2,3],[1,2,3],[1,2,3]]),0,'Example 4';
is same_row_column([[1,2,3],[3,2,1],[3,2,1]]),0,'Example 5';

done_testing();

Task2

We count the numbers which have strictly smaller and greater elements than themselves:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub smaller_greater_element{
  my ($arr) = @_;
  my ($min,$max) = ($arr->[0],$arr->[0]);
  ($_ < $min) ? ($min = $_)
    : ($max < $_) && ($max = $_) foreach @$arr;
  @$arr - grep {$min == $_ || $max == $_} @$arr
}

is smaller_greater_element([2,4]),0,'Example 1';
is smaller_greater_element([1,1,1,1]),0,'Example 2';
is smaller_greater_element([1,1,4,8,12,12]),2,'Example 3';
is smaller_greater_element([3,6,6,9]),2,'Example 4';
is smaller_greater_element([0,-5,10,-2,4]),3,'Example 5';

done_testing();