Skip to content

Commit 99b71d3

Browse files
committed
Merge pull request prakhar1989#28 from vedangmehta/patch-9
Create shuffle.py
2 parents 78089ba + 7f6c652 commit 99b71d3

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

misc/shuffle.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
Fisher-Yates shuffle algorithm implemented in Python.
3+
4+
Reference :
5+
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
6+
http://www.geeksforgeeks.org/shuffle-a-given-array/
7+
8+
Algorithm:
9+
For all N indices of list, swap the element at a given index i with the element at a random index j where 0 <= j <= i.
10+
"""
11+
12+
from random import randint
13+
14+
def shuffle(arr):
15+
"""
16+
Shuffle a list.
17+
"""
18+
for i in range(0,len(arr)):
19+
r = randint(0,i)
20+
arr[i],arr[r] = arr[r],arr[i]
21+
22+
if __name__ == '__main__':
23+
arr = [1,2,3,4,5,6]
24+
shuffle(arr)
25+
print(arr)

0 commit comments

Comments
 (0)