Sunday, March 17, 2024

TWC261

Challenge Link

Task1

We subtract the sum of each digit in each number from the sum of the numbers and take its absolute value:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0);

sub element_digit_sum{
  abs(sum0(map{split ''}@{$_[0]}) - sum0(@{$_[0]}))
}

printf "%d\n",element_digit_sum([1,2,3,45]);
printf "%d\n",element_digit_sum([1,12,3]);
printf "%d\n",element_digit_sum([1,2,3,4]);
printf "%d\n",element_digit_sum([236,416,336,350]);

Task2

While $start is in the list, we keep multiplying it by 2:

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

sub multiply_by_two{
  my ($arr,$start) = @_;
  $start *= 2 while((firstidx{$start == $_}@$arr)!=-1);
  $start
}

printf "%d\n",multiply_by_two([5,3,6,1,12],3);
printf "%d\n",multiply_by_two([1,2,4,3],1);
printf "%d\n",multiply_by_two([5,6,7],2);

No comments:

Post a Comment