0

I'm creating a 50 states study app (To help me for school), and I want each choice of a state to have it's own random option. So I have an Array holding all of the state's. Is there anyway I can select randomly select a variable from this Array then drop the variable I just used (That way it's not used again). But I want It to take the minimum amount of data, because It will be in my game loop. Which is run 60 times per second (60 FPS). Any Ideas? Here is what I'v thought of:

String.valueOf(stateVariables.get(random.nextInt(3))) //It has four variables in it, so three is the max.

But this doesn't stop the variable it selects from being used again. Please Help!

Elgin Beloy
  • 93
  • 1
  • 6

2 Answers2

0

Not sure if understood your question, but after selecting a array position, you want to exclude it and never be selected again? If so, you can't delete an array position. What you can do is set this position to null, so when you pick it again, it'll return null and you'll know it have already been selected.

public int getRandom(int i) {
  int randomNumber = array[i];
  array[i] = null;
  return randomNumber;
}

int selectedNumber = getRandom(3);
if (selectedNumber == null)
  System.out.println("Number already selected");
else
  System.out.println("Number never selected; can be used");
Fagundes
  • 119
  • 10
0

If i understand you right, you are concerned about the performance during your game loop. I have a performant idea in mind. You could create an array with all indices and shuffle it randomely before running the game loop. Safe that array as some subclass of java.util.Queue. Then when the game loop runs you can just remove the first element of that Queue and select it from the array.

As every index is only once in the Queue it will not be reselected and the remove function from a Queue is pretty performant therefore you will not have to worry about that. Only the initialization of that Queue is relatively performance intense, however still in milliseconds.

findusl
  • 2,454
  • 8
  • 32
  • 51