The weekly challenge 226 - Task 1: Shuffle String

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-226/#TASK1
 3 #
 4 # Task 1: Shuffle String
 5 # ======================
 6 #
 7 # You are given a string and an array of indices of same length as string.
 8 #
 9 # Write a script to return the string after re-arranging the indices in the correct order.
10 #
11 ## Example 1
12 ##
13 ## Input: $string = 'lacelengh', @indices = (3,2,0,5,4,8,6,7,1)
14 ## Output: 'challenge'
15 #
16 ## Example 2
17 ##
18 ## Input: $string = 'rulepark', @indices = (4,7,3,1,0,5,2,6)
19 ## Output: 'perlraku'
20 #
21 ############################################################
22 ##
23 ## discussion
24 ##
25 ############################################################
26 #
27 # Split the string into an array of characters, then walk that
28 # array and assign each character to the corresponding index of
29 # a new array.
30 
31 use strict;
32 use warnings;
33 
34 shuffle_string('lacelengh', 3,2,0,5,4,8,6,7,1);
35 shuffle_string('rulepark', 4,7,3,1,0,5,2,6);
36 
37 sub shuffle_string {
38    my ($string, @indices) = @_;
39    print "Input: '$string', (" . join(",", @indices) . ")\n";
40    my @chars = split //, $string;
41    my @new = ();
42    foreach my $i (0..$#chars) {
43       $new[$indices[$i]] = $chars[$i];
44    }
45    print "Output: '" . join("",@new) . "'\n";
46 }
47