Implement an in-place shuffling algorithm

I believe this may be the Fisher-Yates shuffle, but I'm not sure.
This commit is contained in:
William Carroll 2020-03-06 17:54:15 +00:00
parent a9ac4f925b
commit b04b1dafd2
2 changed files with 22 additions and 2 deletions

View file

@ -0,0 +1,20 @@
import random
def get_random(floor, ceiling):
return random.randrange(floor, ceiling + 1)
def shuffle(xs):
n = len(xs)
for i in range(n - 1):
j = get_random(i + 1, n - 1)
xs[i], xs[j] = xs[j], xs[i]
sample_list = [1, 2, 3, 4, 5]
print('Sample list:', sample_list)
print('Shuffling sample list...')
shuffle(sample_list)
print(sample_list)

View file

@ -13,8 +13,8 @@
** DONE Apple Stocks
** DONE Highest Product of 3
** DONE Product of All Other Numbers
** TODO Cafe Order Checker
** TODO In-Place Shuffle
** DONE Cafe Order Checker
** DONE In-Place Shuffle
* Sorting, searching, and logarithms
** TODO Find Rotation Point
** TODO Find Repeat, Space Edition