Random without repeat

Looking to help a student that wants to do a randomizer app that pulls from a data set of 50 items. He wants the program to display a random list item without repeating until it reaches 50 items, at which point it can loop back around. Basically random with out repeating. Is there a way to do that?

Off the top of my head, I can think of a couple of algorithms.

One is to create a second copy of the data set. Choose a random entry from the copy and then remove that item from the copy. When the copy is empty fill it back up from the original.

Create an array of equal length to the data set and a variable initialized to the length. Set all the elements in the array to false. Randomly choose from the data set and set the corresponding element in the array to true. If the element you chose already matches to true choose again. Then deduct one from the variable. When the variable gets to zero start over with all false and the length of the data set again.

Create an array the same length as the data set. Initialize that array to integers from 0 to the length - 1. Randomly chose from that array and use as the index into the data set. Remove that used index from the array. When the array is empty reinitialize.

You can also modify a couple of these by creating a random array shuffle so that you can shuffle the choices and then just take the next value from the array and remove it.

Create a second data set that is empty. Randomly choose from the original data set. Then move it from the original data set to the empty data set. When all the data is moved to the second data set reverse the process and randomly move them back as you use them a second time. Then start over.

1 Like