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';

No comments:

Post a Comment