Monday, July 31, 2023

TWC228

Challenge Link

Task1

In this task we must remove the duplicate elements from the array, also removing the element which was a duplicate, then take the sum. This can be easily accomplished with a hash to count the frequency of elements:

 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(sum0);

sub unique_sum{
  my %hash;
  $hash{$_}++ foreach(@{$_[0]});
  sum0 grep{$hash{$_} == 1} keys %hash;
}

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


Task2

In this task we must remove the first element if it's the minimum element of the array otherwise we must append it to the array and keep doing this until the array becomes depleted, whilst keeping and returning the count of this operation:

 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(min);

sub empty_array{
  my ($count,$arr) = (0,@_);
  while(@$arr){
    $arr->[0] == min(@$arr) ? shift @$arr : push @$arr,shift @$arr;
    $count++
  }
  $count
}

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

Monday, July 24, 2023

TWC227

 Challenge Link

Task1 

In the first task we must count the number of Friday 13ths and we can do so by iterating months of the given year and checking if the 13th day of each month is a Friday and increment the count. We can use the Time::Piece module for this purpose: 

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

sub friday_13th{
  my ($count,$year) = (0,@_);
  foreach my $month(1..12){
    my $d = Time::Piece->strptime("$year-$month-13", "%Y-%m-%d");
    $count++ if $d->day_of_week == 5;
  }
  $count
}

printf "%d\n", friday_13th(2023);


Task2

For the second task we are asked to do 2-term arithmetic with Roman numerals. We can also use the Roman or Math::Roman modules of cpan for this purpose:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env perl
use strict;
use warnings;
use Roman;

sub roman_maths
{
  my ($n1,$n2,$r) = (arabic($_[0]),arabic($_[2]));
  eval "\$r = $n1 $_[1] $n2;";
  die "Error: $@" if $@;
  if($r != int($r) || $r < 0 || $r > 3999){return "non potest"}
  elsif($r == 0){return "nulla"}
  uc(roman($r));
}

printf "%s\n", roman_maths('IV','+','V');
printf "%s\n", roman_maths('M','-','I');
printf "%s\n", roman_maths('X','/','II');
printf "%s\n", roman_maths('XI','*','VI');
printf "%s\n", roman_maths('VII','**','III');
printf "%s\n", roman_maths('V','-','V');
printf "%s\n", roman_maths('V','/','II');
printf "%s\n", roman_maths('MMM','+','M');
printf "%s\n", roman_maths('V','-','X');