Monday, June 16, 2025

TWC326

Challenge Link

Task1

We find day number using Time::Piece module:
#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;

sub day_of_the_year{
  Time::Piece->strptime($_[0],'%Y-%m-%d')->yday + 1
}

printf "%d\n",day_of_the_year('2025-02-02');
printf "%d\n",day_of_the_year('2025-04-10');
printf "%d\n",day_of_the_year('2025-09-07');

Task2

For each pair of numbers, we append the j value i times to the result:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub decompressed_list{
  my ($arr) = @_;
  my ($i,@res) = (0);
  while($i < $#{$arr}){
    push @res, ($arr->[$i+1]) x $arr->[$i];
    $i += 2
  }
  @res
}

print show decompressed_list([1,3,2,4]);
print show decompressed_list([1,1,2,2]);
print show decompressed_list([3,1,3,2]);

Monday, June 9, 2025

TWC325

Challenge Link

Task1

We find the count of maximum runs of ones:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(max);

sub consecutive_one{
  max 0,map length,split /[^1]+/,join '',@{$_[0]}
}

printf "%d\n",consecutive_one([0,1,1,0,1,1,1]);
printf "%d\n",consecutive_one([0,0,0,0]);
printf "%d\n",consecutive_one([1,0,1,0,1,1]);

Task2

We subtract each price from its immediate smaller price to find the discounts:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub final_price {
  my ($p) = @_;
  my @stack;
  my @res = @$p;
  foreach my $i(0..$#$p){
    while(@stack && ($p->[$stack[-1]] >= $p->[$i])) {
      my $j = pop @stack;
      $res[$j] = $p->[$j] - $p->[$i]
    }
    push @stack,$i
  }
  @res
}

print show final_price([8,4,6,2,3]);
print show final_price([1,2,3,4,5]);
print show final_price([7,1,1,5]);

Monday, June 2, 2025

TWC324

Challenge Link

Task1

We take $c columns from the array each $r time through the map:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub twod_array{
  my ($arr,$r,$c) = @_;
  map{[splice @$arr,0,$c]} 1..$r
}

print show twod_array([1,2,3,4],2,2);
print show twod_array([1,2,3],1,3);
print show twod_array([1,2,3,4],4,1);

Task2

We find the sum of xoring each subset of the array:
#!/usr/bin/env perl
use strict;
use warnings;
use Algorithm::Combinatorics qw(subsets);
use List::Util qw(reduce);

sub total_xor{
  my $it = subsets($_[0]);
  my $sum = 0;
  while(my $s = $it->next){
    $sum += reduce {$a ^ $b} 0, @$s
  }
  $sum
}

printf "%d\n",total_xor([1,3]);
printf "%d\n",total_xor([5,1,6]);
printf "%d\n",total_xor([3,4,5,6,7,8]);