Monday, May 12, 2025

TWC321

Challenge Link

Task1

We sort the array and pair min and max elements, then take their averages and count the distinct ones:
#!/usr/bin/env perl
use strict;
use warnings;

sub distinct_average{
  my @arr = sort{$a <=> $b} @{$_[0]};
  my %h;
  undef $h{($arr[$_] + $arr[$#arr-$_]) / 2} foreach 0..@arr/2;
  scalar keys %h
}

printf "%d\n",distinct_average([1,2,4,3,5,6]);
printf "%d\n",distinct_average([0,2,4,8,3,5]);
printf "%d\n",distinct_average([7,3,1,0,5,9]);

Task2

We transform the strings by removing the characters when we see a # character, and then compare the strings:
#!/usr/bin/env perl
use strict;
use warnings;

sub backspace_compare{
  my ($s1,$s2) = @_;
  for($s1,$s2){
    1 while s/[^#]#//
  }
  $s1 eq $s2
}

printf "%d\n",backspace_compare('ab#c','ad#c');
printf "%d\n",backspace_compare('ab##','a#b#');
printf "%d\n",backspace_compare('a#b','c');

No comments: