Algo-Sim › Math & Geometry

Shuffle an Array

Medium · Math & Geometry · step through it in Java, Python and C++ on your own input

Fisher–Yates: for i from the back, swap a[i] with a uniform j ≤ i. Every one of the n! orderings is equally likely.

Problem

Given an integer array nums, design a class whose shuffle() returns a random permutation of the array in which every permutation is equally likely, and whose reset() returns the array in its original order.

Constraints

Edge cases to test

Follow-up questions

Why is "swap each i with any j" biased?
It has nⁿ equally likely runs, which isn’t divisible by n! for n > 2, so some orderings appear more often.
How do you sample k items without replacement?
Run Fisher–Yates for only k steps: O(k) time after the O(n) copy.

Solution

Java

class Solution {
    private final int[] original;
    private final Random rand = new Random();

    public Solution(int[] nums) {
        original = nums.clone();
    }

    public int[] reset() {
        return original.clone();
    }

    // Fisher–Yates: fill positions from the back with a uniform pick of what is left.
    public int[] shuffle() {
        int[] a = original.clone();
        for (int i = a.length - 1; i > 0; i--) {
            int j = rand.nextInt(i + 1);
            int t = a[i]; a[i] = a[j]; a[j] = t;
        }
        return a;
    }
}

Python

import random


class Solution:
    def __init__(self, nums):
        self.original = nums[:]

    def reset(self):
        return self.original[:]

    # Fisher–Yates: fill positions from the back with a uniform pick of what is left.
    def shuffle(self):
        a = self.original[:]
        for i in range(len(a) - 1, 0, -1):
            j = random.randint(0, i)
            a[i], a[j] = a[j], a[i]
        return a

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
    vector<int> original;

  public:
    Solution(vector<int> &nums) : original(nums) {}

    vector<int> reset() { return original; }

    // Fisher–Yates: fill positions from the back with a uniform pick of what is left.
    vector<int> shuffle() {
        vector<int> a = original;
        for (int i = int(a.size()) - 1; i > 0; i--) {
            int j = rand() % (i + 1);
            swap(a[i], a[j]);
        }
        return a;
    }
};

More Math & Geometry problems