Sunday, November 12, 2023

TWC243

Challenge Link

Task1

We take each two-combination of the list and check if it satisfies the condition:

#!/usr/bin/env perl
use strict;
use warnings;
use Algorithm::Combinatorics qw(combinations);

sub reverse_pairs{
  my $it = combinations($_[0],2);
  my $count = 0;
  while(my $c = $it->next){
    $count++ if $c->[0] > ($c->[1] * 2)
  }
  $count
}

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

Task2

We take each two-pairs of the resultant cross product of the list and accumulate their floor sums:

#!/usr/bin/env perl
use strict;
use warnings;
use Algorithm::Combinatorics qw(variations_with_repetition);

sub floor_sum{
  my $it = variations_with_repetition($_[0],2);
  my $sum = 0;
  while(my $c = $it->next){
    $sum += int($c->[0] / $c->[1]);
  }
  $sum
}

printf "%d\n",floor_sum([2,5,9]);
printf "%d\n",floor_sum([7,7,7,7,7,7,7]);

No comments:

Post a Comment