Fisher-Yates Algorithm

class Solution:
def __init__(self, nums):
self.array = nums
self.original = list(nums)
def reset(self):
self.array = self.original[:]
return self.original
def shuffle(self):
be_chosen_array = self.array[:]
for i in range(len(self.array)):
random_idx = random.randrange(len(be_chosen_array))
# pop from an arbitary location has the complexity of O(n)
self.array[i] = be_chosen_array.pop(random_idx)
return self.array
class Solution:
def __init__(self, nums):
self.array = nums
self.original = list(nums)
def reset(self):
self.array = self.original[:]
return self.original
def shuffle(self):
N = len(self.array)
for i in range(N):
j = random.randrange(N)
# swap has the complexity of O(1), i == j is allowed.
self.array[i], self.array[j] = self.array[j], self.array[i]
return self.array

--

--

--

Data Scientist/MLE/SWE @takemobi

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Calculate the SVD from Scratch with Python

Working on Professional Skills for Civil Engineering

Go: Asynchronous Preemption

Simple Player Movement in Unity

What are the possibilities in 4th dimension?

UX Case Study: An Accessible Ride-Sharing Ecosystem

Mock up screen’s of an accessible ride-sharing ecosystem

湯姆貓與傑利鼠▷ 完整版本(2021-ZH) Tom and Jerry 完整版-bluray!!

Titles CRODO

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jimmy Shen

Jimmy Shen

Data Scientist/MLE/SWE @takemobi

More from Medium

Predicting Credit Card Approval using Machine Learning

Binary Search Algorithm

Dijkstra’s algorithm

Into the world of Open Source contribution