Monday, April 1, 2024

TWC263

Challenge Link

Task1

We sort the array then return the indices of the elements equal to k:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub target_index{
  my @sorted = sort{$a <=> $b} @{$_[0]};
  map{$sorted[$_] == $_[1] ? $_ : ()}0..$#{$_[0]};
}

print show target_index([1,5,3,2,4,2],2);
print show target_index([1,2,4,3,5],6);
print show target_index([5,3,2,4,2,1],4);

Task2

We add each quantity to the count of ids in the hash and return the keys and values of the hash:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub merge_items{
  my %h;
  $h{$_->[0]} += $_->[1] foreach(@{$_[0]},@{$_[1]});
  map{[$_,$h{$_}]} sort{$a <=> $b} keys %h;
}

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

No comments:

Post a Comment