Created
September 26, 2019 20:31
-
-
Save indapa/224595b39e944878fb73b40da45189cc to your computer and use it in GitHub Desktop.
Shuffle an array with Fisher-Yates shuffle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Shuffle an array with Fisher-Yates shuffle | |
""" | |
Given input N generate a random permutation of 1 to N. | |
Example: N=5 Output: 1 5 2 4 3 | |
Based on this post https://www.geeksforgeeks.org/generate-a-random-permutation-of-1-to-n/ | |
""" | |
import random | |
def swap(x,m,n): | |
temp=x[m] | |
x[m] = x[n] | |
x[n]=temp | |
def rand_perm(N): | |
x = range(1,N+1) | |
#print x | |
for i in xrange(N-1, 0, -1): | |
j=random.randint(0,i) | |
#print i,j | |
swap(x,i,j) | |
print x | |
rand_perm(20) | |
B |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment