The weekly challenge 263 - Task 2: Merge Items

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-263/#TASK2
 3 #
 4 # Task 2: Merge Items
 5 # ===================
 6 #
 7 # You are given two 2-D array of positive integers, $items1 and $items2 where
 8 # element is pair of (item_id, item_quantity).
 9 #
10 # Write a script to return the merged items.
11 #
12 ## Example 1
13 ##
14 ## Input: $items1 = [ [1,1], [2,1], [3,2] ]
15 ##        $items2 = [ [2,2], [1,3] ]
16 ## Output: [ [1,4], [2,3], [3,2] ]
17 ##
18 ## Item id (1) appears 2 times: [1,1] and [1,3]. Merged item now (1,4)
19 ## Item id (2) appears 2 times: [2,1] and [2,2]. Merged item now (2,3)
20 ## Item id (3) appears 1 time: [3,2]
21 #
22 ## Example 2
23 ##
24 ## Input: $items1 = [ [1,2], [2,3], [1,3], [3,2] ]
25 ##        $items2 = [ [3,1], [1,3] ]
26 ## Output: [ [1,8], [2,3], [3,3] ]
27 #
28 ## Example 3
29 ##
30 ## Input: $items1 = [ [1,1], [2,2], [3,3] ]
31 ##        $items2 = [ [2,3], [2,4] ]
32 ## Output: [ [1,1], [2,9], [3,3] ]
33 #
34 ############################################################
35 ##
36 ## discussion
37 ##
38 ############################################################
39 #
40 # For this one, actually printing input and output is a little
41 # more tricky than the actual algorithm: Simply walk the combination
42 # of both arrays, and for each entry use the first element of that
43 # as the key of a result hash and the second element as what to add
44 # to the value of that entry in the hash. Print the result sorted
45 # by the hash keys.
46 
47 use strict;
48 use warnings;
49 
50 merge_items( [ [1,1], [2,1], [3,2] ], [ [2,2], [1,3] ] );
51 merge_items( [ [1,2], [2,3], [1,3], [3,2] ], [ [3,1], [1,3] ] );
52 merge_items( [ [1,1], [2,2], [3,3] ], [ [2,3], [2,4] ] );
53 
54 sub merge_items {
55    my ($items1, $items2) = @_;
56    my $result;
57    print "Input: item1: [";
58    foreach my $elem (@$items1) {
59       print "[$elem->[0], $elem->[1]],";
60    }
61    print "],\n";
62    print "       item2: [";
63    foreach my $elem (@$items2) {
64       print "[$elem->[0], $elem->[1]],";
65    }
66    print "]\n";
67 
68    foreach my $elem( (@$items1, @$items2) ) {
69       $result->{$elem->[0]} += $elem->[1];
70    }
71 
72    print "Output: [";
73    foreach my $elem (sort {$a <=> $b} keys %$result) {
74       print "[$elem, $result->{$elem}],";
75    }
76    print "]\n";
77 }