Wednesday, September 3, 2025

TWC337

Challenge Link

Task1

We count the numbers which are less than each element and store them at that element's index:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;
use List::Util qw(sum0);
use List::MoreUtils qw(frequency);

sub smaller_than_current{
  my %h = frequency(@{$_[0]});
  my @arr;
  foreach my $i(0..$#{$_[0]}) {
    my %h2 = %h{grep{$_ <= $_[0]->[$i]} keys %h};
    @arr[$i] = sum0(values %h2) - 1
  }
  @arr
}

print show smaller_than_current([6,5,4,8]);
print show smaller_than_current([7,7,7,7]);
print show smaller_than_current([5,4,3,2,1]);
print show smaller_than_current([-1,0,3,-2,1]);
print show smaller_than_current([0,1,1,2,0]);

Task2

We do the simulation on a row x col matrix and count the odd numbers:
#!/usr/bin/env perl
use strict;
use warnings;

sub odd_matrix{
  my ($row,$col,$m) = @_;
  my @g;
  push @g,[(0) x $col] foreach(0..$row-1);
  foreach my $p(@$m){
    foreach(0..$col-1) {
      ++$g[$p->[0]]->[$_]
    }
    foreach(0..$row-1){
      ++$g[$_]->[$p->[1]]
    }
  }
  my $res = 0;
  foreach my $i(0..$row-1){
    foreach my $j(0..$col-1) {
      $res++ if $g[$i][$j] % 2
    }
  }
  $res
}

printf "%d\n", odd_matrix(2,3,[[0,1],[1,1]]);
printf "%d\n", odd_matrix(2,2,[[1,1],[0,0]]);
printf "%d\n", odd_matrix(3,3,[[0,0],[1,2],[2,1]]);
printf "%d\n", odd_matrix(1,5,[[0,2],[0,4]]);
printf "%d\n", odd_matrix(4,2,[[1,0],[3,1],[2,0],[0,1]]);

No comments:

Post a Comment