Sunday, March 10, 2024

TWC260

Challenge Link

Task1

We count the occurrences of each integer in a hash, then check if the length of the values of that hash is equal to the length of the unique values,  if so we return 1 else 0:

#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(uniq all);

sub unique_occurences{
  my %h;
  $h{$_}++ foreach @{$_[0]};
  my @values = values %h;
  @values == (uniq @values) || 0
}

printf "%d\n",unique_occurences([1,2,2,1,1,3]);
printf "%d\n",unique_occurences([1,2,3]);
printf "%d\n",unique_occurences([-2,0,1,-2,1,1,0,1,-2,9]);

Task2

We construct an array of all permutations of the given string, join each tuple to a string, and remove the duplicates, then sort and find the index of the string which is equal to the argument of the subroutine:
#!/usr/bin/env perl
use strict;
use warnings;
use Algorithm::Combinatorics qw(permutations);
use List::MoreUtils qw(onlyidx uniq);

sub dictionary_rank{
  1+onlyidx{$_ eq $_[0]}
    sort{$a cmp $b}
    uniq map{join'',@$_}
    permutations([split '',$_[0]])
}

printf "%d\n",dictionary_rank('CAT');
printf "%d\n",dictionary_rank('GOOGLE');
printf "%d\n",dictionary_rank('SECRET');

No comments:

Post a Comment