Skip to content

Instantly share code, notes, and snippets.

@cnocon
Last active December 11, 2015 05:28
Show Gist options
  • Save cnocon/4551963 to your computer and use it in GitHub Desktop.
Save cnocon/4551963 to your computer and use it in GitHub Desktop.
Ch. 10 Shuffle Exercise From "Learning to Program" by Chris Pine.
#still trying to figure out why my shuffled array returns one too few words
puts 'Please enter a list of comma separated words that you would like to shuffle.'
unshuffled = gets.chomp.downcase.split(',')
shuffled = []
indeces = []
def shuffler unshuffled, shuffled, indeces
unshuffled.each do |word|
if unshuffled.length == 1
shuffled[0] == unshuffled.pop
return shuffled
elsif indeces.length == 0
i = rand(unshuffled.length).to_i
word = unshuffled.pop
shuffled[i] = word
indeces.push(i)
elsif unshuffled.length == 0
return shuffled
else
i = rand(unshuffled.length).to_i
end
end
end
puts shuffler unshuffled, shuffled, indeces
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment