perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 396 - Task 1: Finishing Order

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-396/#TASK1
 3 #
 4 # Task 1: Finishing Order
 5 # =======================
 6 #
 7 # You are given two array of integers, @order and @friends.
 8 #
 9 # The @order (size n) contains every integer from 1 to n exactly once. The
10 # @friends contains ID in sorted in strictly increasing order.
11 #
12 # Write a script to return the array containing IDs in finishing order.
13 #
14 ## Example 1
15 ##
16 ## Input: @order = (3, 1, 4, 2, 5)
17 ##        @friends = (1, 2, 4)
18 ## Output: (1, 4, 2)
19 ##
20 ## ID 1 finished 2nd.
21 ## ID 4 finished 3rd.
22 ## ID 2 finished 4th.
23 #
24 ## Example 2
25 ##
26 ## Input: @order = (5, 4, 3, 2, 1)
27 ##        @friends = (1, 3, 5)
28 ## Output: (5, 3, 1)
29 ##
30 ## ID 5 finished 1st.
31 ## ID 3 finished 3rd.
32 ## ID 1 finished 5th.
33 #
34 ## Example 3
35 ##
36 ## Input: @order = (2, 4, 1, 3)
37 ##        @friends = (1, 2, 3, 4)
38 ## Output: (2, 4, 1, 3)
39 ##
40 ## ID 2 finished 1st.
41 ## ID 4 finished 2nd.
42 ## ID 1 finished 3rd.
43 ## ID 3 finished 4th.
44 #
45 ## Example 4
46 ##
47 ## Input: @order = (4, 1, 3, 2)
48 ##        @friends = (3)
49 ## Output: (3)
50 #
51 ## Example 5
52 ##
53 ## Input: @order = (1, 3, 2, 6, 5, 4)
54 ##        @friends = (1, 2, 3)
55 ## Output: (1, 3, 2)
56 ##
57 ## ID 1 finished 1st.
58 ## ID 3 finished 2nd.
59 ## ID 2 finished 3rd.
60 #
61 ############################################################
62 ##
63 ## discussion
64 ##
65 ############################################################
66 #
67 # Since the order is given by @order, we just fill a hash with the index
68 # for the order and use that hash to sort the @friends.
69 
70 use v5.36;
71 
72 sub finishing_order($order, $friends) {
73     say "Input: (" . join(", ", @$order) . "), (" . join(", ", @$friends) . ")";
74     my $idx = 0;
75     my $ordered = {};
76     foreach my $elem (@$order) {
77         $idx++;
78         $ordered->{$elem} = $idx;
79     }
80     say "Output: (" . join(", ", sort { $ordered->{$a} <=> $ordered->{$b} } @$friends) . ")";
81 }
82 
83 finishing_order( [3, 1, 4, 2, 5], [1, 2, 4]);
84 finishing_order( [5, 4, 3, 2, 1], [1, 3, 5]);
85 finishing_order( [2, 4, 1, 3], [1, 2, 3, 4]);
86 finishing_order( [4, 1, 3, 2], [3]);
87 finishing_order( [1, 3, 2, 6, 5, 4], [1, 2, 3]);