Sunday, December 3, 2023

TWC245

Challenge Link

Task1

Subtract 1 from popularity indices and index the array to get a sorted array by popularity:

#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub sort_language{
  @{$_[0]}[map{$_-1}@{$_[1]}];
}

print show sort_language(['perl','c','python'],[2,1,3]);
print show sort_language(['c++','haskell','java'],[1,3,2]);


Task2

We iterate over each permutation of subsets of the array and check for the given condition:

#!/usr/bin/env perl
use strict;
use warnings;
use Algorithm::Combinatorics qw(permutations subsets);

sub largest_of_three{
  my $res = -1;
  foreach my $i(0..@{$_[0]}){
    foreach my $subset(subsets $_[0],$i){
      foreach my $p(permutations $subset){
        next unless @$p;
        my $n = join '',@$p;
        $res = $n if $n > $res && $n % 3 == 0;
      }
    }
  }
  $res
}

printf "%d\n",largest_of_three([8,1,9]);
printf "%d\n",largest_of_three([8,6,7,1,0]);
printf "%d\n",largest_of_three([1]);


No comments:

Post a Comment