Sunday, August 6, 2023

TWC229

 Challenge Link

Task1

We are asked to delete the elements which are not lexicographically sorted forwards and backwards, and return the count of the deletions. We are actually not deleting anything from the array in the code, just counting them.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#!/usr/bin/env perl
use strict;
use warnings;

sub lexicographic_order
{
  my $count = 0;
  map{
    my $s = join '',sort split '';
    $count++ if(($s ne $_) && (reverse($s) ne $_))} @{$_[0]};
  $count;
}

printf "%d\n",lexicographic_order(["abc", "bce", "cae"]);
printf "%d\n",lexicographic_order(["yxz", "cba", "mon"]);

Task2

We are asked to return the elements present at least in 2 of the arrays, so this is a simple intersection which can be accomplished by counting the elements' occurrences with a hash.

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

sub two_out_of_three
{
  my %hash;
  map{$hash{$_}++ foreach uniq @$_} @{$_[0]};
  sort{$a <=> $b} grep{$hash{$_} >= 2} keys %hash
}

printf "(%s)\n", join ',' => two_out_of_three([[1,1,2,4],[2,4],[4]]);
printf "(%s)\n", join ',' => two_out_of_three([[4,1],[2,4],[1,2]]);

No comments:

Post a Comment