Thursday, October 12, 2023

TWC238

Challenge Link

Task1

We iterate the array and add the current sum to the return value on each iteration:

#!/usr/bin/env perl
use strict;
use warnings;

sub running_sum{
  my $sum = 0;
  map{$sum += $_[0]->[$_]} 0..$#{$_[0]}
}

printf "(%s)\n",join ',',running_sum([1,2,3,4,5]);
printf "(%s)\n",join ',',running_sum([1,1,1,1,1]);
printf "(%s)\n",join ',',running_sum([0,-1,1,2]);

Task2

If the sort's helper returns 0 (meaning the items are equal after helper returns), the rhs of the <=> is used for sorting:

#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(product);

sub persistence_sort{
  my $helper = sub{
    my ($sum,$n) = (0,@_);
    $n = do{$sum++; product split '',$n} until $n < 10;
    $sum
  };
  sort{$helper->($a) <=> $helper->($b) || $a <=> $b} @{$_[0]}
}

printf "(%s)\n",join ',',persistence_sort([15,99,1,34]);
printf "(%s)\n",join ',',persistence_sort([50,25,33,22]);

No comments:

Post a Comment