Wednesday, September 13, 2023

TWC234

Challenge Link

Task1

We are asked to find the common characters in all words including duplicates. First we count the characters of each string in a hash, then we take the first string's letters and their counts and see if they are duplicated in other ones and find the minimum of that which gives us the number of times that character needs to be repeated:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(min);

sub common_characters{
  my @letters;
  map{my %h; $h{$_}++ for split ''; push @letters,\%h} @{$_[0]};
  map{my $letter = $_;
      my $rep = min map{$letters[$_]{$letter} // 0} 0..$#letters;
      ($letter) x $rep
    } keys %{$letters[0]};
}

printf "(%s)\n", join ',',
  common_characters([qw/java javascript julia/]);
printf "(%s)\n", join ',',
  common_characters([qw/bella label roller/]);
printf "(%s)\n", join ',', common_characters([qw/cool lock cook/]);


Task2

We are asked to find the triplets (i,j,k) such that num[i] != num[j], num[j] != num[k], and num[k] != num[i]. First we find the unique items of the list, if the result is less than 3 items, then the answer would be zero since we don't have 3 items, else we find the sum of the product of every 3 item combinations of those items for the answer:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0 product);
use Algorithm::Combinatorics qw(combinations);

sub unequal_triplets{
  my %h;
  $h{$_}++ foreach @{$_[0]};
  my @keys = keys %h;
  @keys < 3 ? 0 : sum0 map{product @h{@$_}} combinations(\@keys,3);
}

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

No comments:

Post a Comment