Monday, October 30, 2023

TWC241

Challenge Link

Task1

We iterate every three-combination of the array and check if it satisfies the given condition:
#!/usr/bin/env perl
use strict;
use warnings;
use Algorithm::Combinatorics qw(combinations);

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

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

Task2

We sort the array according to the number of prime factors of its elements, or the elements themselves in case the result is 0:
#!/usr/bin/env perl
use strict;
use warnings;
use ntheory qw(factor);

sub prime_order{
  sort{factor($a) <=> factor($b) || $a <=> $b} @{$_[0]};		
}

printf "(%s)\n", join ',',prime_order([11,8,27,4]);

No comments:

Post a Comment