Monday, October 13, 2025

TWC343

Challenge Link

Task1

We find the number with the smallest distance from zero:
#!/usr/bin/env perl
use strict;
use warnings;

sub zero_friend{
  my $zf = abs shift @{$_[0]};
  abs $_ < $zf and $zf = abs for @{$_[0]};
  $zf
}

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

Task2

We count the wins and find the champion team:
#!/usr/bin/env perl
use strict;
use warnings;

sub champion_team{
  my $m = 0;
  my %h;
  foreach my $y(0..$#{$_[0]}){
    foreach my $x(0..$#{$_[0]->[$y]}){
      my $w = $_[0]->[$y][$x] ? $y : $x;
      $m = $w if ++$h{$w} > $h{$m}
    }
  }
  $m
}

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

0 comments:

Post a Comment