Just [[currentUser.getNumFreeQuestionsLeft()]] No more free questions left!

Upgrade Now

Write a function for doing an in-place shuffle of an array.

The shuffle must be "uniform," meaning each item in the original array must have the same probability of ending up in each spot in the final array.

Assume that you have a function getRandom(floor, ceiling) for getting a random integer that is >= floor and <= ceiling.

A common first idea is to walk through the array and swap each element with a random other element. Like so:

import java.util.Random; public int getRandom(int floor, int ceiling) { Random rand = new Random(); return rand.nextInt((ceiling - floor) + 1) + floor; } public void naiveShuffle(int[] theArray) { // for each index in the array for (int firstIndex = 0; firstIndex < theArray.length; firstIndex++) { // grab a random other index int secondIndex = getRandom(0, theArray.length - 1); // and swap the values if (secondIndex != firstIndex) { int temp = theArray[firstIndex]; theArray[firstIndex] = theArray[secondIndex]; theArray[secondIndex] = temp; } } }

However, this does not give a uniform random distribution.

Why? We could calculate the exact probabilities of two outcomes to show they aren't the same. But the math gets a little messy. Instead, think of it this way:

Suppose our array had 3 elements: [a,b,c]. This means it'll make 3 calls to getRandom(0, 2). That's 3 random choices, each with 3 possibilities. So our total number of possible sets of choices is 3*3*3=27. Each of these 27 sets of choices is equally probable.

But how many possible outcomes do we have? If you paid attention in stats class you might know the answer is 3!, which is 6. Or you can just list them by hand and count:

a,b,c a,c,b b,a,c b,c,a c,b,a c,a,b

But our function has 27 equally-probable sets of choices. 27 is not evenly divisible by 6. So some of our 6 possible outcomes will be achievable with more sets of choices than others.

We can do this in a single pass. time and space.

A common mistake is to have a mostly-uniform shuffle where an item is less likely to stay where it started than it is to end up in any given slot. Each item should have the same probability of ending up in each spot, including the spot where it starts.

You must log in with one click to view the rest.

Once you're logged in, you'll get free full access to this and 4 other questions.

You must log in with one click to view the rest.

Once you're logged in, you'll get free full access to this and 4 other questions.

time and space.

You must log in with one click to view the rest.

Once you're logged in, you'll get free full access to this and 4 other questions.

What's next?

RUN
Code execution powered by Qualified.io

. . .