Thursday, October 5, 2023

TWC237

Challenge Link

Task1

We are given a year,a month, a weekday of month and a day of week and we must print the corresponding day. The Nth_Weekday_of_Month_Year subroutine of the Date::Calc module can be used for this purpose:

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

sub seize_the_day{
  my ($y,$m,$mday,$wday) = @_;
  (Nth_Weekday_of_Month_Year($y,$m,$wday,$mday))[2] // 0;
}

printf "%d\n",seize_the_day(2024,4,3,2);
printf "%d\n",seize_the_day(2025,10,2,4);
printf "%d\n",seize_the_day(2026,8,5,3);


Task2

We are asked to find the maximum count of when the arr[i] < perm[i] for all permutations of the given array:

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

sub maximise_greatness{
  my ($arr) = @_;
  my $max = 0;
  my $iter = permutations($arr);
  while(my $c = $iter->next){
    my $count = grep{$arr->[$_] < $c->[$_]} 0..$#$arr;
    $max = $count if $count > $max;
  }
  $max
}

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

No comments:

Post a Comment