You have an array of numbers, how do you shuffle them?
Or, You have a playlist of songs how do you shuffle them?

The shuffling method is called
Fisher yates shuffling
The method is you take the array then generate a random number from 0 to len(array) take the number in that index(remove the number) and put this number in another array. Now do exactly same with the new array with one less element.

You can do this in place also: The modification is simple you take the number by the index generated in first step and then put this number in the end of the array (swap the end number of the array with the index generated.

in Python shuffling is done by

import random
list = [i for i in range(1,53)]

Fisher yates

We can implement fisher yates in place:

import random
li = [i for i in range(1,53)]

#generate a random number in range 0,52(exclusive)
for i in range(52):
  index = random.randint(0,51-i)
  temp = li[index]
  li[index] = li[52-i - 1]
  li[52-i-1] = temp


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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s