Wednesday, July 10, 2024

TWC277

Challenge Link

Task1

We count the array elements in a hash and check which ones are equal to two:

#!/usr/bin/env perl
use strict;
use warnings;

sub count_common{
  my %h;
  $h{$_}++ foreach @{$_[0]},@{$_[1]};
  (grep{$_ == 2}values %h) // 0
}

printf "%d\n",
  count_common(['Perl','is','my','friend'],
	       ['Perl','and','Raku','are','friend']);
printf "%d\n",
  count_common(['Perl','and','Python','are','very','similar'],
	       ['Python','is','top','in','guest','languages']);
printf "%d\n",
  count_common(['Perl','is','imperative','Lisp','is','functional'],
	       ['Crystal','is','similar','to','Ruby']);

Task2

We count how many times the given condition is met, for each combination of pairs of elements:

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

sub strong_pairs{
  scalar grep{abs($$_[0] - $$_[1]) < min(@$_)}
    combinations([uniq @{$_[0]}],2)
}

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

No comments:

Post a Comment