Skip to content

Instantly share code, notes, and snippets.

@hnq90
Created July 29, 2015 02:30
Show Gist options
  • Select an option

  • Save hnq90/2fa2883afd9ebd7bf994 to your computer and use it in GitHub Desktop.

Select an option

Save hnq90/2fa2883afd9ebd7bf994 to your computer and use it in GitHub Desktop.
def get_random(floor, ceiling):
return random.randrange(floor, ceiling + 1)
def shuffle(the_array):
# if it's 1 or 0 items, just return
if len(the_array) <= 1:
return the_array
last_index_in_the_array = len(the_array) - 1
# walk through from beginning to end
for index_we_are_choosing_for in xrange(0, len(the_array)):
# choose a random not-yet-placed item to place there
# (could also be the item currently in that spot)
# must be an item AFTER the current item, because the stuff
# before has all already been placed
random_choice_index = get_random(index_we_are_choosing_for, last_index_in_the_array)
# place our random choice in the spot by swapping
the_array[index_we_are_choosing_for], the_array[random_choice_index] = the_array[random_choice_index], the_array[index_we_are_choosing_for]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment