Shuffle an Array in Python

Suppose we have an array A, we have to shuffle a set of numbers without duplicates. So if the input is like [1,2,3], then for shuffling, it will be [1,3,2], after resetting, if we shuffle again, it will be [2,3,1]

To solve this, we will follow these steps −

  • There will be different methods. these are init(), reset(), shuffle(). These will act like below −

  • init will be like −

  • original := a copy of the given array

  • temp := nums

  • indices := a list of numbers from 0 to length of nums – 1

  • the reset() will return the original array

  • the shuffle() will be like −

  • if length of temp is 0, then return empty array

  • i := choice randomly one index from indices array, j := choose another index from indices array randomly

  • swap the elements present at index i and j

  • return temp

  • another method called getAllPermutation() will take nums, i, initially i = 0, will be like −

  • curr := i

  • if i = length of nums, then

    • insert a copy of nums array into another array called all

    • return

  • for j := curr to length of nums

    • swap elements at index j and curr from nums

    • call getAllPermutation(nums, curr + 1)

    • swap elements at index j and curr from nums

Let us see the following implementation to get better understanding −


 Live Demo

import random
class Solution(object):
   def __init__(self, nums):
      self.original = [x for x in nums]
      self.temp = nums
      self.indices = [x for x in range(len(nums))]
   def reset(self):
      return self.original
   def shuffle(self):
      if not len(self.temp):
         return []
      i = random.choice(self.indices)
      j = random.choice(self.indices)
      self.temp[i], self.temp[j] = self.temp[j], self.temp[i]
      return self.temp
ob = Solution([1,2,3])


Initialize with [1,2,3] , then call shuffle(), reset() and shuffle()


[2, 1, 3]
[1, 2, 3]
[2, 3, 1]