[ create a new paste ] login | about

Link: http://codepad.org/0I2Y1Osz    [ raw code | output | fork ]

Perl, pasted on Oct 22:
#!/usr/bin/perl

# Shuffle array
# Ed Siok
# 10/22/2009
# 
# We're going to try to shuffle an array by replacing each value with a random
# value further ahead in the array that the value we are shuffling

@originalArray = qw(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15);
$debug = 0;

# First we want to get a random value from the list

debug ("# values in originalArray: $#originalArray");
for ($i=0; $i<$#originalArray; $i++) {
  my $randomNumber = int(rand($#originalArray+1-$i))+$i;
  debug ("random number: $randomNumber");
  #Got a random number that represents the cell we want to replace with
  my $tempVal = @originalArray[$i];
  @originalArray[$i] = @originalArray[$randomNumber];
  @originalArray[$randomNumber] = $tempVal;
}

print ("Here's the array: @originalArray");

sub debug {
  my $stringToPrint = shift;
  print "$stringToPrint" unless !$debug;
  return;
}


Output:
1
Here's the array: 15 12 9 0 3 10 8 6 1 7 13 2 11 4 14 5


Create a new paste based on this one


Comments: