The Weekly Challenge - 263


TASK #1: Target Index
You are given an array of integers, @ints and a target element $k.

Write a script to return the list of indices in the sorted array where the element is same as the given target element.


Here my solution, without keyword 'my', without validating arguments subroutine, without a module:


sub mc_target_index {
 ($k_, @ints_) = @_;  	

  @ints_sorted = ();
  @ints_sorted = sort( { $a <=> $b } @ints_ );
  join(", ", grep { $ints_sorted[$_] == $k_ } 0 .. $#ints_sorted);
}

@ints = (1, 5, 3, 2, 4, 2);
$k = 2;
print("\(", mc_target_index($k, @ints), ")\n"); # Output: (1,2)

@ints = (1, 2, 4, 3, 5);
$k = 6;
print("\(", mc_target_index($k, @ints), ")\n"); # Output: ()

@ints = (5, 3, 2, 4, 2, 1);
$k = 4;
print("\(", mc_target_index($k, @ints), ")\n"); # Output: (4)

TASK #2: Merge Items
You are given two 2-D array of positive integers, $items1 and $items2 where element is pair of (item_id, item_quantity).

Write a script to return the merged items.


Here my solution, without keyword 'my', without validating arguments subroutine and $k, without a module and a tip: have a look at 10. Useful Hash applications:

sub mc_merge_items {
  	
  ($aref1, $aref2) = @_;
  @combined_arrays = (@$aref1, @$aref2);
  
  %res = ();
  foreach ( @combined_arrays ) {
    $res{$_->[0]} += $_->[1]; 
  }

  $output = "";
  foreach $k (sort(keys(%res))) {
    $output .= " [$k,$res{$k}], ";
  }

  substr($output, -2, length($output), ' '); # remove comma at the end of $output in order to produce the requested output
  print("[$output]\n");
}


$items1 = [ [1,1], [2,1], [3,2] ];
$items2 = [ [2,2], [1,3] ];
mc_merge_items($items1, $items2); # Output: [ [1,4], [2,3], [3,2] ]


$items1 = [ [1,2], [2,3], [1,3], [3,2] ];
$items2 = [ [3,1], [1,3] ];
mc_merge_items($items1, $items2); # Output: [ [1,8], [2,3], [3,3] ]


$items1 = [ [1,1], [2,2], [3,3] ];
$items2 = [ [2,3], [2,4] ];
mc_merge_items($items1, $items2); # Output: [ [1,1], [2,9], [3,3] ]