The weekly challenge 263 - Task 1: Target Index

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-263/#TASK1
 3 #
 4 # Task 1: Target Index
 5 # ====================
 6 #
 7 # You are given an array of integers, @ints and a target element $k.
 8 #
 9 # Write a script to return the list of indices in the sorted array where the
10 # element is same as the given target element.
11 #
12 ## Example 1
13 ##
14 ## Input: @ints = (1, 5, 3, 2, 4, 2), $k = 2
15 ## Output: (1, 2)
16 ##
17 ## Sorted array: (1, 2, 2, 3, 4, 5)
18 ## Target indices: (1, 2) as $ints[1] = 2 and $k[2] = 2
19 #
20 ## Example 2
21 ##
22 ## Input: @ints = (1, 2, 4, 3, 5), $k = 6
23 ## Output: ()
24 ##
25 ## No element in the given array matching the given target.
26 #
27 ## Example 3
28 ##
29 ## Input: @ints = (5, 3, 2, 4, 2, 1), $k = 4
30 ## Output: (4)
31 ##
32 ## Sorted array: (1, 2, 2, 3, 4, 5)
33 ## Target index: (4) as $ints[4] = 4
34 #
35 ############################################################
36 ##
37 ## discussion
38 ##
39 ############################################################
40 #
41 # Straight forward steps: sort the input array, use an index to
42 # walk the array and remember the instances where $ints[$i] == $k.
43 
44 use strict;
45 use warnings;
46 
47 target_index( [1, 5, 3, 2, 4, 2], 2);
48 target_index( [1, 2, 4, 3, 5], 6);
49 target_index( [5, 3, 2, 4, 2, 1], 4);
50 
51 sub target_index {
52    my ($ints, $k) = @_;
53    print "Input: (" . join(", ", @$ints) . ")\n";
54    my @result = ();
55    my @sorted = sort @$ints;
56    foreach my $i (0..$#sorted) {
57       if($sorted[$i] == $k) {
58          push @result, $i;
59       }
60    }
61    print "Output: (" . join(", ", @result) . ")\n";
62 }