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

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();

Sunday, July 5, 2026

TWC377

Challenge Link

Task1

We check if a pair of chars exists in the reverse of the given string:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub reverse_existence{
  0 + $_[0] =~ /(?=(.)(.))(?=.*\2\1)/
}

is reverse_existence('abcba'),1,'Example 1';
is reverse_existence('racecar'),1,'Example 2';
is reverse_existence('abcd'),0,'Example 3';
is reverse_existence('banana'),1,'Example 4';
is reverse_existence('hello'),1,'Example 5';

done_testing();

Task2

We count strings which are both prefix and suffix of another one:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 6;

sub prefix_suffix{
  my ($arr) = @_;
  my %h;
  foreach my $i(0..$#$arr){
    my $s1 = $arr->[$i];
    foreach my $j($i+1..$#$arr){
      my $s2 = $arr->[$j];
      next if 0 != index($s2,$s1)
	|| abs(length($s2) - length($s1)) != rindex $s2,$s1;
      undef $h{join ':',sort {$a <=> $b} $i,$j}
    }
  }
  scalar keys %h
}

is prefix_suffix(['a','aba','ababa','aa']),4,'Example 1';
is prefix_suffix(['pa','papa','ma','mama']),2,'Example 2';
is prefix_suffix(['abao','ab']),0,'Example 3';
is prefix_suffix(['abab','abab']),1,'Example 4';
is prefix_suffix(['ab','abab','ababab']),3,'Example 5';
is prefix_suffix(['abc','def','ghij']),0,'Example 6';

done_testing();

Saturday, July 4, 2026

TWC374

Challenge Link

Task1

We return the substrings which consists of vowels and has all 5 of them:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub count_vowel{
  my @res;
  my $len = length $_[0];
  foreach my $s(0..$len-1){
    foreach my $l(5..$len-$s){
      my $sub = substr($_[0],$s,$l);
      next unless $sub =~ /^[aeiou]+$/;
      next unless (5 == grep {$sub =~ /$_/} qw(a e i o u));
      push @res,$sub
    }
  }
  \@res
}

is_deeply count_vowel('aeiou'),['aeiou'],'Example 1';
is_deeply count_vowel('aaeeeiioouu'),
  ['aaeeeiioou','aaeeeiioouu','aeeeiioou','aeeeiioouu'],'Example 2';
is_deeply count_vowel('aeiouuaxaeiou'),
  ['aeiou','aeiouu','aeiouua','eiouua','aeiou'],'Example 3';
is_deeply count_vowel('uaeiou'),['uaeio','uaeiou','aeiou'],'Example 4';
is_deeply count_vowel('aeioaeioa'),[],'Example 5';

done_testing();

Task2

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

sub largest_same_digit_number{
  my $r = -1;
  while($_[0] =~ /((.)\2*)/g){
    $r = $1 if $r < $1
  }
  0 + $r
}

is largest_same_digit_number('6777133339'),3333,'Example 1';
is largest_same_digit_number('1200034'),4,'Example 2';
is largest_same_digit_number('44221155'),55,'Example 3';
is largest_same_digit_number('88888'),88888,'Example 4';
is largest_same_digit_number('11122233'),222,'Example 5';

done_testing();

TWC372

Challenge Link

Task1

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

sub rearrange_spaces{
  my $c = $_[0] =~ tr/ //;
  my @words = split ' ',$_[0];
  my $width = @words > 1 ? int($c / $#words) : 0;
  my $rest = @words > 1 ? $c % $#words : $c;
  join(' ' x $width,@words) . ' ' x $rest
}

is rearrange_spaces('  challenge  '),'challenge    ','Example 1';
is rearrange_spaces('coding  is  fun'),'coding  is  fun','Example 2';
is rearrange_spaces('a b c  d'),'a b c d ','Example 3';
is rearrange_spaces('  team      pwc  '),
  'team          pwc','Example 4';
is rearrange_spaces('   the  weekly  challenge  '),
  'the    weekly    challenge ','Example 5';

Task2

We find the largest substring in-between two equal characters:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub largest_string{
  my $l = 0;
  $l < length $2 and $l = length $2 while $_[0] =~ /(.)(?=(.*)\1)/g;
  $l
}

is largest_string('aaaaa'),3,'Example 1';
is largest_string('abcdeba'),5,'Example 2';
is largest_string('abbc'),0,'Example 3';
is largest_string('abcaacbc'),4,'Example 4';
is largest_string('laptop'),2,'Example 5';

Monday, June 29, 2026

TWC380

Challenge Link

Task1

We count the maximum frequencies of vowels and consonants and sum them:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(max);
use Test::More tests => 5;

sub sum_of_frequencies {
  my %h;
  $h{$_}++ foreach split '', lc $_[0];
  my ($c, $v) = (0, 0);
  foreach (keys %h) {
    /[aeiou]/ ? ($v = max($v, $h{$_})) : ($c = max($c, $h{$_}));
  }
  $c + $v;
}

is sum_of_frequencies('banana'),5,'Example 1';
is sum_of_frequencies('teestett'),7,'Example 2';
is sum_of_frequencies('aeiouuaa'),3,'Example 3';
is sum_of_frequencies('rhythm'),2,'Example 4';
is sum_of_frequencies('x'),1,'Example 5';

Task2

We calculate the score of each letter according to its position in the string and reverse alphabet enumeration and then sum the result:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0);
use Test::More tests => 5;

sub reverse_degree{
  my ($i,%h) = (1);
  @h{'a'..'z'} = reverse 1..26;
  sum0 map {$h{$_} * $i++} split '',lc $_[0]
}

is reverse_degree('z'),1,'Example 1';
is reverse_degree('a'),26,'Example 2';
is reverse_degree('bbc'),147,'Example 3';
is reverse_degree('racecar'),560,'Example 4';
is reverse_degree('zyx'),14,'Example 5';

done_testing();

Sunday, June 28, 2026

TWC368

Challenge Link

Task1

We find the index of the number which if removed, makes the number the maximum possible:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(max);
use Test::More tests => 5;

sub make_it_bigger{
  my $idx = -1;
  my @res;
  while(($idx = index $_[0],$_[1],$idx+1) != -1){
    substr my $s = $_[0],$idx,1,'';
    push @res,$s
  }
  max(@res)
}

is make_it_bigger('15456','5'),'1546','Example 1';
is make_it_bigger('7332','3'),'732','Example 2';
is make_it_bigger('2231','2'),'231','Example 3';
is make_it_bigger('543251','5'),'54321','Example 4';
is make_it_bigger('1921','1'),'921','Example 5';

Task2

We calculate the little or big omega of the number according to the given instructions:
#!/usr/bin/env perl
use strict;
use warnings;
use ntheory qw(factor factor_exp);
use Test::More tests => 5;

sub big_and_little_omega{
  my @funcs = (\&factor_exp,\&factor);
  scalar($funcs[!!$_[1]]($_[0]))
}

is big_and_little_omega(100061,0),3,'Example 1';
is big_and_little_omega(971088,0),3,'Example 2';
is big_and_little_omega(63640,1),6,'Example 3';
is big_and_little_omega(988841,1),2,'Example 4';
is big_and_little_omega(211529,0),2,'Example 5';

Saturday, June 27, 2026

TWC366

Challenge Link

Task1

We count the strings which are prefixes of the given string:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub count_prefixes{
  scalar grep {index($_[1], $_) == 0} @{$_[0]}
}

is count_prefixes(['a','ap','app','apple','banana'],'apple'),
  4,'Example 1';
is count_prefixes(['cat','dog','fish'],'bird'),0,'Example 2';
is count_prefixes(['hello','he','hell','heaven','he'],'hello'),
  4,'Example 3';
is count_prefixes(['','code','coding','cod'],'coding'),
  3,'Example 4';
is count_prefixes(['p','pr','pro','prog','progr','progra','program'],
		  'program'),7,'Example 5';

Task2

We check for valid times by enumerating different possibilities of hours and minutes:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub valid_times{
  my $res = 1;
  my @t = split '',$_[0];
  if($t[0] eq '?') {
    $res = $t[1] eq '?' ? 24 : $t[1] lt '4' ? 3 : 2
  } elsif($t[1] eq '?') {
    $res = $t[0] lt '2' ? 10 : 4
  }
  $res * ($t[3] eq '?' ? 6 : 1) * ($t[4] eq '?' ? 10 : 1)
}

is valid_times('?2:34'),3,'Example 1';
is valid_times('?4:?0'),12,'Example 2';
is valid_times('??:??'),1440,'Example 3';
is valid_times('?3:45'),3,'Example 4';
is valid_times('2?:15'),4,'Example 5';

Friday, June 26, 2026

TWC365

Challenge Link

Task1

We assign to each letter its positional value and sum its digits k times:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub digits_sum{
  my ($n) = @_;
  my $sum = 0;
  while($n > 0){
    $sum += $n % 10;
    $n /= 10
  }
  $sum
}

sub alphabet_index_digit_sum{
  my $n = '';
  foreach(split '',$_[0]){
    $n .= int(ord($_) - ord('a') + 1)
  }
  for(my $i = 0; $i < $_[1]; ++$i){
    $n = digits_sum($n)
  }
  $n
}

is alphabet_index_digit_sum('abc',1),6,'Example 1';
is alphabet_index_digit_sum('az',2),9,'Example 2';
is alphabet_index_digit_sum('cat',1),6,'Example 3';
is alphabet_index_digit_sum('dog',2),8,'Example 4';
is alphabet_index_digit_sum('perl',3),6,'Example 5';

Task2

We check for the given conditions and count each word that satisfies it:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub valid_token_counter{
  scalar grep {/^(?:[a-z]+-)?[a-z]+[?!.,]?$/} split /\s+/,$_[0];
}

is valid_token_counter("cat and dog"),3,'Example 1';
is valid_token_counter("a-b c! d,e"),2,'Example 2';
is valid_token_counter("hello-world! this is fun"),4,'Example 3';
is valid_token_counter("ab- cd-ef gh- ij!"),2,'Example 4';
is valid_token_counter("wow! a-b-c nice."),2,'Example 5';

Thursday, June 25, 2026

TWC364

Challenge Link

Task1

We decrypt the string according to the given rules, were single digits are handled differently from two-digit sequences:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub decrypt_string{
  my %h;
  my ($i,$c) = (1,'a');
  $h{$i++} = $c++ foreach 1..9;
  $h{$i++ . '#'} = $c++ foreach 10..26;
  $_[0] =~ s/((?:1\d|2[0-6])#|\d)/$h{$1}/gr
}

is decrypt_string('10#11#12'),'jkab','Example 1';
is decrypt_string('1326#'),'acz','Example 2';
is decrypt_string('25#24#123'),'yxabc','Example 3';
is decrypt_string('20#5'),'te','Example 4';
is decrypt_string('1910#26#'),'aijz','Example 5';

Task2

We replace "()" with "o" and "(al)" with "al":
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;

sub goal_parser{
  my %h = ('' => 'o',al => 'al');
  $_[0] =~ s/\(((?:al)?)\)/$h{$1}/gr
}

is goal_parser('G()(al)'),'Goal','Example 1';
is goal_parser('G()()()()(al)'),'Gooooal','Example 2';
is goal_parser('(al)G(al)()()'),'alGaloo','Example 3';
is goal_parser('()G()G'),'oGoG','Example 4';
is goal_parser('(al)(al)G()()'),'alalGoo','Example 5';

Tuesday, June 23, 2026

TWC379

Challenge Link

Task1

We reverse the string:
#!/usr/bin/env perl
use strict;
use warnings;

sub reverse_string{
  my ($s) = @_;
  my $res = '';
  $res .= chop $s while length $s;
  $res
}

printf "%s\n",reverse_string('');
printf "%s\n",reverse_string('reverse the given string');
printf "%s\n",reverse_string('Perl is Awesome');
printf "%s\n",reverse_string('v1.0.0-Beta!');
printf "%s\n",reverse_string('racecar');

Task2

We find all armstrong numbers under the given limit:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub is_armstrong{
  my ($base,$limit) = @_;
  grep{
    my ($v,$sum,@digits) = (0,0,split '',$_);
    $v = $v * $base + $_,$sum += $_ ** @digits for @digits;
    $v == $sum
  } 0..$limit
}

show is_armstrong(10,1000);
show is_armstrong(7,1000);
show is_armstrong(16,1000);

Wednesday, June 17, 2026

TWC373

Challenge Link

Task1

We concatenate two string lists to strings and check for equality:
#!/usr/bin/env perl
use strict;
use warnings;

sub equal_list{
  (join '',@{$_[0]}) eq (join '',@{$_[1]})
}

printf "%d\n",equal_list(['a','bc'],['ab','c']);
printf "%d\n",equal_list(['a','b','c'],['a','bc']);
printf "%d\n",equal_list(['a','bc'],['a','c','b']);
printf "%d\n",equal_list(['ab','c',''],['','a','bc']);
printf "%d\n",equal_list(['p','e','r','l'],['perl']);

Task2

We try to divide the list two equal parts as long as possible:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub list_division{
  my ($arr,$n) = @_;
  my $sz = int(@$arr / $n);
  return -1 if $n > @$arr;

  my $rest = @$arr % $n;
  my @res;
  foreach my $i(1..$n){
    push @res,[splice @$arr,0,$sz + ($i <= $rest)]
  }
  @res
}

show list_division([1..5],2);
show list_division([1..6],3);
show list_division([1..3],2);
show list_division([1..10],5);
show list_division([1..3],4);
show list_division([72,57,89,55,36,84,10,95,99,35],7);

Monday, June 15, 2026

TWC378

Challenge Link

Task1

We find the second largest number after filtering alphabetic characters:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(uniq);
use Data::Show;

sub second_largest_digit{
  (sort {$b <=> $a} uniq $_[0] =~ /\d/g)[1] // -1
}

show second_largest_digit('aaaaa77777');
show second_largest_digit('abcde');
show second_largest_digit('9zero8eight7seven9');
show second_largest_digit('xyz9876543210');
show second_largest_digit('4abc4def2ghi8jkl2');

Task2

We calculate the sum of each character and see if the sum of first two is equal the third string:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;
use List::Util qw(reduce);

sub f{
  reduce {$a * 10 - (ord($b) - ord('a'))} 0, split '',$_[0];
}

sub sum_of_words{
  f($_[0]) + f($_[1]) == f($_[2])
}

show sum_of_words('acb','cba','cdb');
show sum_of_words('aab','aac','ad');
show sum_of_words('bc','je','jg');
show sum_of_words('a','aaaa','aa');
show sum_of_words('c','d','h');
show sum_of_words('gfi','hbf','bdhd');

Sunday, February 22, 2026

TWC362

Challenge Link

Task1

We repeat each letter i times:
#!/usr/bin/env perl
use strict;
use warnings;

sub echo_chamber{
  my ($s) = @_;
  my @res;
  foreach my $i(0..length($s)-1) {
    push @res,substr($s,$i,1) x ($i+1)
  }
  join '',@res
}

printf "%s\n",echo_chamber('abca');
printf "%s\n",echo_chamber('xyz');
printf "%s\n",echo_chamber('code');
printf "%s\n",echo_chamber('hello');
printf "%s\n",echo_chamber('a');

Task2

We spell out the numbers according to this algorithm:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub to_en{
  my ($n) = @_;
  return 'minus ' . to_en(-$n) if $n < 0;
  my @units = qw(zero one two three four five six seven eight nine);
  my %teens = (10 => 'ten',11 => 'eleven',12 => 'twelve',
	       13 => 'thirteen',14 => 'fourteen', 15 => 'fifteen',
	       16 => 'sixteen',17 => 'seventeen', 18 => 'eighteen',
	       19 => 'nineteen');
  my %tens = (20 => 'twenty',30 => 'thirty', 40 => 'forty',
	      50 => 'fifty',60 => 'sixty',70 => 'seventy',
	      80 => 'eighty',90 => 'ninety');

  return $units[$n] if $n < 10;
  return $teens{$n} if $n < 20;

  if($n < 100) {
    my $t = int($n / 10) * 10;
    my $u = $n % 10;
    return $u == 0 ? $tens{$t} : "$tens{$t}-$units[$u]"
  }

  if($n < 1000) {
    my $h = int($n/100);
    my $r = $n % 100;
    my $base = "$units[$h] hundred";
    return $r == 0 ? $base : "$base and " . to_en($r)
  }
  
  if($n < 1_000_000) {
    my $th = int($n/1000);
    my $r = $n % 1000;
    my $base = to_en($th) . ' thousand';
    return $r == 0 ? $base : "$base " . to_en($r)
  }

  die "Number is out of supported range\n"
}

sub spellbound_sorting{
  my ($arr) = @_;
  my %words;
  foreach my $n(@$arr){$words{$n} = to_en($n)}
  sort {$words{$a} cmp $words{$b}} @$arr
}

show spellbound_sorting([6,7,8,9,10]);
show spellbound_sorting([-3,0,1000,99]);
show spellbound_sorting([1,2,3,4,5]);
show spellbound_sorting([0,-1,-2,-3,-4]);
show spellbound_sorting([100,101,102]);

Monday, February 16, 2026

TWC361

Challenge Link

Task1

We calculate the zeckendorf representation of the given number:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub zeckendorf_representation{
  my ($n) = @_;
  my @fibs = (1,2);
  push @fibs,$fibs[-1] + $fibs[-2] while($fibs[-1] + $fibs[-2] <= $n);
  
  my ($i,$rem,@parts) = ($#fibs,$n);
  while($rem) {
    if($fibs[$i] <= $rem) {
      push @parts,$fibs[$i];
      $rem -= $fibs[$i];
      $i -= 2;
    } else {
      --$i
    }
  }
  @parts
}

show zeckendorf_representation(4);
show zeckendorf_representation(12);
show zeckendorf_representation(20);
show zeckendorf_representation(96);
show zeckendorf_representation(100);

Task2

We find person who doesn't know anybody else:
#!/usr/bin/env perl
use strict;
use warnings;

sub find_celebrity{
  my ($party) = @_;
  my $n = @$party;
  return -1 if $n == 0;

  my $cand = 0;
  foreach my $i(1..$n-1) {
    $cand = $i if($party->[$cand][$i]);
  }
  
  foreach my $i(0..$n-1) {
    next if $i == $cand;
    return -1 if($party->[$cand][$i] || !$party->[$i][$cand]);
  }
  $cand
}

printf "%d\n",find_celebrity([[0,0,0,0,1,0],
			      [0,0,0,0,1,0],
			      [0,0,0,0,1,0],
			      [0,0,0,0,1,0],
			      [0,0,0,0,0,0],
			      [0,0,0,0,1,0]]);
printf "%d\n",find_celebrity([[0,1,0,0],
			      [0,0,1,0],
			      [0,0,0,1],
			      [1,0,0,0]]);
printf "%d\n",find_celebrity([[0,0,0,0,0],
			      [1,0,0,0,0],
			      [1,0,0,0,0],
			      [1,0,0,0,0],
			      [1,0,0,0,0]]);
printf "%d\n",find_celebrity([[0,1,0,1,0,1],
			      [1,0,1,1,0,0],
			      [0,0,0,1,1,0],
			      [0,0,0,0,0,0],
			      [0,1,0,1,0,0],
			      [1,0,1,1,0,0]]);
printf "%d\n",find_celebrity([[0,1,1,0],
			      [1,0,1,0],
			      [0,0,0,0],
			      [0,0,0,0]]);
printf "%d\n",find_celebrity([[0,0,1,1],
			      [1,0,0,0],
			      [1,1,0,1],
			      [1,1,0,0]]);

Monday, February 9, 2026

TWC360

Challenge Link

Task1

We justify the text according to the given width:
#!/usr/bin/env perl
use strict;
use warnings;

sub text_justifier{
  my $diff = $_[1] - length($_[0]);
  die "Length too short!" if($diff < 0);
  my $l = int($diff / 2);
  my $r = $diff - $l;
  '*' x $l . $_[0] . '*' x $r
}

printf "%s\n",text_justifier('Hi',5);
printf "%s\n",text_justifier('Code',10);
printf "%s\n",text_justifier('Hello',9);
printf "%s\n",text_justifier('Perl',4);
printf "%s\n",text_justifier('A',7);
printf "%s\n",text_justifier('',5);

Task2

We sort the case-folded words and join them back into a string:
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw(fc);

sub word_sorter{
  join ' ',sort {fc($a) cmp fc($b)} split /\s+/,$_[0];
}

printf "%s\n",word_sorter('The quick brown fox');
printf "%s\n",word_sorter('Hello    World!   How   are you?');
printf "%s\n",word_sorter('Hello');
printf "%s\n",word_sorter('Hello, World! How are you?');
printf "%s\n",word_sorter('I have 2 apples and 3 bananas!');

Sunday, February 8, 2026

TWC359

Challenge Link

Task1

We keep on summing the digits of the number until we reach a number with a single digit:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0);

sub digital_root {
  my ($n) = @_;
  my $c = 0;
  $c++, $n = sum0 split '',$n while $n > 9;
  printf "Persistence  = %d\nDigital Root = %d\n",$c,$n
}

digital_root(38);
digital_root(7);
digital_root(999);
digital_root(1999999999);
digital_root(101010);

Task2

We keep on removing duplicate characters until there's none:

#!/usr/bin/env perl
use strict;
use warnings;

sub string_reduction{
  my ($s) = @_;
  1 while $s =~ s/(\w)\1//g;
  $s
}

printf "%s\n",string_reduction('aabbccdd');
printf "%s\n",string_reduction('abccba');
printf "%s\n",string_reduction('abcdef');
printf "%s\n",string_reduction('aabbaeaccdd');
printf "%s\n",string_reduction('mississippi');

Sunday, December 28, 2025

TWC353

Challenge Link

Task1

We find the sentence with maximum words:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(max);

sub max_words{
  max map{scalar split} @{$_[0]}
}

printf "%d\n",max_words(['Hello world',
			 'This is a test','Perl is great']);
printf "%d\n",max_words(['Single']);
printf "%d\n",max_words(['Short',
			 'This sentence has six words in total',
			 'A B C',
			 'Just four words here']);
printf "%d\n",max_words(['One','Two parts','Three part phrase','']);
printf "%d\n",max_words(['The quick brown fox jumps over the lazy dog',
			 'A',
			 'She sells seashells by the seashore',
			 'To be or not to be that is the question']);

Task2

We simulate the solution and check for the given conditions:
#!/usr/bin/env perl
use strict;
use warnings;

sub validate_coupon{
  my %valid;
  @valid{qw(electronics grocery pharmacy restaurant)} = 1;
  map {$_[0]->[$_] =~ /^[_0-9a-zA-Z]+$/ &&
	 exists $valid{$_[1]->[$_]} &&
	 $_[2]->[$_] eq 'true' ? 1 : 0} 0..$#{$_[0]}
}

printf "(%s)\n", join ',',
  validate_coupon(['A123','B_456','C789','D@1','E123'],
		  ['electronics','restaurant','electronics',
		   'pharmacy','grocery'],
		  ['true','false','true','true','true']);
printf "(%s)\n", join ',',
  validate_coupon(['Z_9','AB_12','G01','X99','test'],
		  ['pharmacy','electronics','grocery',
		   'electronics','unknown'],
		  ['true','true','false','true','true']);
printf "(%s)\n", join ',',
  validate_coupon(['_123','123','','Coupon_A','Alpha'],
		  ['restaurant','electronics','electronics',
		   'pharmacy','grocery'],
		  ['true','true','false','true','true']);
printf "(%s)\n", join ',',
  validate_coupon(['ITEM_1','ITEM_2','ITEM_3','ITEM_4'],
		  ['electronics','electronics','grocery','grocery'],
		  ['true','true','true','true']);
printf "(%s)\n", join ',',
  validate_coupon(['CAFE_X','ELEC_100','FOOD_1','DRUG_A','ELEC_99'],
		  ['restaurant','electronics','grocery',
		   'pharmacy','electronics'],
		  ['true','true','true','true','false']);

Monday, December 15, 2025

TWC352

Challenge Link

Task1

We return every string that is a substring of amother:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(any);

sub match_string{
  my ($arr) = @_;
  my @res;
  foreach my $i(0..$#$arr) {
    my $x = $arr->[$i];
    foreach my $j(0..$#$arr) {
      my $y = $arr->[$j];
      if($i != $j && index($y,$x) != -1 && !any{$_ eq $x} @res) {
	push @res,$x;
	last
      }
    }
  }
  @res
}

printf "(%s)\n",join ', ',match_string(['cat','cats','dog','dogcat',
				       'dogcat','rat','ratcatdogcat']);
printf "(%s)\n",join ', ',
  match_string(['hello','hell','world','wor','ellow','elloworld']);
printf "(%s)\n",join ', ',
  match_string(['a', 'aa', 'aaa', 'aaaa']);
printf "(%s)\n",join ', ',
  match_string(['flower','flow','flight','fl','fli','ig','ght']);
printf "(%s)\n",join ', ',
  match_string(['car','carpet','carpenter','pet',
		'enter','pen','pent']);

Task2

We check if the accumulated binary number is divisible by 5 and accumulate the boolean results in an array:
#!/usr/bin/env perl
use strict;
use warnings;

sub binary_prefix{
  my @res;
  my $x = 0;
  foreach(@{$_[0]}){
    $x = ($x << 1 | $_) % 5;
    push @res,$x == 0 ? 1 : 0;
  }
  @res
}

printf "(%s)\n", join ', ', binary_prefix([0,1,1,0,0,1,0,1,1,1]);
printf "(%s)\n", join ', ', binary_prefix([1,0,1,0,1,0]);
printf "(%s)\n", join ', ', binary_prefix([0,0,1,0,1]);
printf "(%s)\n", join ', ', binary_prefix([1,1,1,1,1]);
printf "(%s)\n", join ', ', binary_prefix([1,0,1,1,0,1,0,0,1,1]);

Friday, December 12, 2025

TWC351

Challenge Link

Task1

We sort the array and remove the minimum and maximum elements then take the average:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0);

sub special_average{
  my ($arr) = @_;
  return 0 if @$arr < 2;
  @$arr = sort {$a <=> $b} @$arr;
  my @sub = splice @$arr,1,$#$arr-1;
  (sum0 @sub) / @sub
}

printf "%d\n",special_average([8000,5000,6000,2000,3000,7000]);
printf "%d\n",special_average([100_000,80_000,110_000,90_000]);
printf "%d\n",special_average([2500,2500,2500,2500]);
printf "%d\n",special_average([2000]);
printf "%d\n",special_average([1000,2000,3000,4000,5000,6000]);

Task2

We sort the array and then check if the distance of all elements is the same:
#!/usr/bin/env perl
use strict;
use warnings;

sub arithmetic_progression{
  my ($arr) = @_;
  @$arr = sort {$a <=> $b} @$arr;
  my $d = abs(shift(@$arr) - shift(@$arr));
  for(my $i = 0; $i < $#$arr-1; ++$i){
    return 0 if abs($arr->[$i] - $arr->[$i+1]) != $d
  }
  1
}

printf "%d\n",arithmetic_progression([1,3,5,7,9]);
printf "%d\n",arithmetic_progression([9,1,7,5,3]);
printf "%d\n",arithmetic_progression([1,2,4,8,16]);
printf "%d\n",arithmetic_progression([5,-1,3,1,-3]);
printf "%d\n",arithmetic_progression([1.5,3,0,4.5,6]);