Life as Clay

Learn to Program: Create a shuffle method

leave a comment »

Page 89 of the Learn to Program book by Chris Pine includes an exercise to write a method that will shuffle an array. I wrote the code for this very quickly, only to discover that the code mutated the original list entered by the user. I played around for a while with writing a method that would take the original list as a parameter, copy it, and then shuffle and return the results of the copy instead of affecting the original list passed to it. The reason I did that is because I wanted to run the method on the original list multiple times so that I could easily inspect the output.

That turned out to be more difficult than I thought.  I discovered that if I created array_two by using the code array_two = array_one, that calling array_one.slice(x) also would remove x from array_two. I didn’t think that variables worked this way, but I guess that arrays aren’t variables. Hey, it was a good thing to learn. I dug through several of my books before I ended up with the following code. What it does is to iterate through the items in the original array and assign them to an array that I then slice to create the shuffled array, leaving the original intact. I used the array.insert() method to accomplish that. I’m sure there is a more efficient way to accomplish this, but this seems to work.

If you have a better idea, please let me know.

def shuffle array
  x = array.length

  # this is here so that we don't affect the original array
  change = []
  y = 0

  x.times do
    change.insert(y, array[y])
    y += 1

  # this is where we create the shuffled array
  shuffled = []

  while x > 0
    y = rand(x)
    shuffled.push change.slice!(y)
    x -= 1

  return shuffled


# Gather the list
puts 'Enter a list item then return. Enter return on a blank line to shuffle:'
list = []
entry = gets.chomp

while entry != ''
  list.push entry
  entry = gets.chomp

# Determine how many times we want to shuffle
x = 0

while x < 1
  puts 'How many versions of the shuffled list do you want to show? (enter a number then return)'
  x = gets.chomp.to_i

# Show the original list
puts 'Original: ' + list.join(', ')

# Show the shuffled lists
x.times do
  puts 'Shuffled: ' + shuffle(list).join(', ')


Written by Clay

October 10, 2009 at 17:21

Posted in Code, Ruby

Tagged with , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: