The weekly challenge 240: Task 2: Build Array

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-240/#TASK2
 3 #
 4 # Task 2: Build Array
 5 # ===================
 6 #
 7 # You are given an array of integers.
 8 #
 9 # Write a script to create an array such that new[i] = old[old[i]] where 0 <= i < new.length.
10 #
11 ## Example 1
12 ##
13 ## Input: @int = (0, 2, 1, 5, 3, 4)
14 ## Output: (0, 1, 2, 4, 5, 3)
15 #
16 ## Example 2
17 ##
18 ## Input: @int = (5, 0, 1, 2, 3, 4)
19 ## Output: (4, 5, 0, 1, 2, 3)
20 #
21 ############################################################
22 ##
23 ## discussion
24 ##
25 ############################################################
26 #
27 # Just loop from 0 to the index of the last element and apply the rule
28 
29 use strict;
30 use warnings;
31 
32 build_array(0, 2, 1, 5, 3, 4);
33 build_array(5, 0, 1, 2, 3, 4);
34 
35 sub build_array {
36    my @int = @_;
37    print "Input: (" . join(", ", @int) . ")\n";
38    my @new = ();
39    foreach my $i (0..$#int) {
40       $new[$i] = $int[$int[$i]];
41    }
42    print "Output: (" . join(", ", @new) . ")\n";
43 }