int numberTrue=0; //adjust this in your other code accordingly
Random r = new Random ();
int rand = r.nextInt (24);
// loop until not true found or stop if all items are true
while (array [rand] && numberTrue < 24) {
rand = r.nextInt (24);
count++;
}
I thought about it for a bit, and without knowing your code here are a couple of suggestions to avoid that infinite loop when they are all true (assuming that condition may exist):
1. keep a count of how many true are set (example adjusted for this)
2. Store a second array of the true indexes, as suggested in the other answer
The first is probably the simplest to implement (adding a numberTrue++;
and numberTrue--;
in the appropriate code spots) - just a note here that if it's not possible to keep this count, you can achieve the same thing by running an initial for loop over your array and counting the number of true elements.
The second way would lend itself to utilizing one of the answers from the other post:
public int generateRandom(int start, int end, ArrayList<Integer> excludeRows) {
Random rand = new Random();
int range = end - start + 1;
int random = rand.nextInt(range) + 1;
while(excludeRows.contains(random)) {
random = rand.nextInt(range) + 1;
}
return random;
}
(I believe their code should actually read rand.nextInt(range) + start
So you would run:
if (trueIndexes.length < 24) {
generateRandom(0, 23, trueIndexes);
}