Skip to content

Commit 5ed4fcb

Browse files
committed
Create shuffle.py
1 parent 78089ba commit 5ed4fcb

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

misc/shuffle.py

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

0 commit comments

Comments
 (0)