## 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.originaldef 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.originaldef 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`

--

--

--

## More from Jimmy Shen

Data Scientist/MLE/SWE @takemobi

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

## Jimmy Shen

Data Scientist/MLE/SWE @takemobi