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]);

No comments:

Post a Comment