Skip to content

Instantly share code, notes, and snippets.

@JFFail
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JFFail/a3ab518886362308f2cb to your computer and use it in GitHub Desktop.
Save JFFail/a3ab518886362308f2cb to your computer and use it in GitHub Desktop.
Solution To Reddit Daily Programmer #224 - Shuffling A List
!/usr/bin/env perl
use warnings;
use strict;
sub shuffle_stuff {
#Turn the values into an array.
my $values = shift;
my @values = split(" ", $values);
#Figure out length. Create an array of index and a final value array.
my $length = @values;
my @holder_array = (0..($length-1));
my @final_array = (0..($length-1));
#Make the index array have values that initially match the index.
for(my $i = 0; $i < $length; $i++) {
$holder_array[$i] = $i;
}
#Shuffle the values to new indexes in the final array.
foreach my $item(@values) {
#Redo the length since it'll change after each iteration.
$length = @holder_array;
#Make a random number in the bounds of the length.
my $index = int(rand($length));
#Assign the current value to a location in the final array.
$final_array[$holder_array[$index]] = $item;
#Splice that index value out of the holder array.
splice(@holder_array, $index, 1);
}
#Print the values.
foreach my $item(@final_array) {
print "$item ";
}
print "\n";
}
#Get the initial input.
my $numbers= "1 2 3 4 5 6 7 8";
my $words= "apple blackberry cherry dragonfruit grapefruit kumquat mango nectarine persimmon raspberry raspberry";
my $letters = "a e i o u";
#Pass them to the function to shuffle.
shuffle_stuff($numbers);
shuffle_stuff($words);
shuffle_stuff($letters);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment