Java – Randomly selecting a unique element in a 2D Array

algorithmjava

Hi so I'm doing an assignment but I've kind of fallen flat on the concept of 2D arrays. I'm writing a method body that randomly selects an element in a 2D array. However, I'm not completely sure when of how to approach the problem.

I was thinking of using a random number generator to select a random element. Although what I need first is for the whole length of the box to be filled first with a value. In this case, the dimensions of the 2D array box are 20×20 and the value is zero. So I'd want the 2D array to be complete filled with zeroes. Although if I used a random number generator, is there a chance that an element which was randomly selected by the generator could possibly be used again before the entire box dimensions are filled first with zero?

Sorry for the long block of text. Basically what I'm asking is if there is a way to use random number generator to still randomly generate numbers but not repeat any its used previously.

Best Answer

One option is to use Collections.shuffle(allCells).

Another option is to use the following algorithm, by keeping track of remaining unused cells:

1. Find a random number from 0 to size of the set - 1 .
2. Remove number at position `randomNumber` from the set.
3. Go to 1.