/
ch-2.pl
executable file
·91 lines (76 loc) · 2.32 KB
/
ch-2.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/perl
use strict;
use warnings;
use English;
################################################################################
# Begin main execution
################################################################################
my @ordered_pair_sets = (
[
[ 0, 1, 2, 3, 4 ],
[ 0, 1, 2, 2, 1 ]
],
[
[ 1, 2, 3, 4, 0 ],
[ 0, 1, 2, 3, 0 ]
],
[
[ 1 ],
[ 0 ]
]
);
print("\n");
foreach my $ordered_pair_set (@ordered_pair_sets){
printf(
"Input: \@source = (%s)\n"
.
" \@indices = (%s)\n"
.
"Output: (%s)\n\n",
join(", ", @{$ordered_pair_set->[0]}),
join(", ", @{$ordered_pair_set->[1]}),
join(", ", create_ordered_array($ordered_pair_set))
);
}
exit(0);
################################################################################
# End main execution; subroutines follow
################################################################################
################################################################################
# Create an array based on particular numbers and a set of indices that
# indicate where the numbers should be inserted into said array
# Takes one argument:
# * A ref to a pair of parallel arrays containing numbers to insert into the
# target array, and the indices at which these numbers must be inserted (e.g.
# [
# [ 0, 1, 2, 3, 4 ],
# [ 0, 1, 2, 2, 1 ]
# ]
# )
# Returns:
# * The constructed list based on the supplied index/number pairs (e.g.
# ( 0, 4, 1, 3, 2 ) )
################################################################################
sub create_ordered_array{
my @target;
# Loop over the supplied index/number
# pairs
for my $i (0 .. $#{$ARG[0][0]}){
if($ARG[0][1][$i] > $#target){
# The given index is outside the array-
# append the number to the end
push(@target, $ARG[0][0][$i]);
} else{
# The given index is within the array-
# insert the number ahead of the value
# currently at that location
splice(
@target,
$ARG[0][1][$i],
1,
($ARG[0][0][$i], $target[$ARG[0][1][$i]])
);
}
}
return(@target);
}