chility chility - 10 days ago 5
Android Question

Can't avoid generating the same random in do while

I have this array that holds some strings:

String[] funnyRiddles = { "1", "2", "3", "4" };


Now I'm trying to generate a random number and show the content of the above array(
funnyRiddles[rand]
), But I would like to stop generating randoms when I have shown all the values of the
funnyRiddles
array with the code below:

Random rnd = new Random();
int randomRiddle = 0;
int clickCounter = 0;
static ArrayList<Integer> passedQuestions = new ArrayList<Integer>();
final RiddlesHolder riddles = (RiddlesHolder) getActivity().getApplication();
askBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (txtAnswer.getText().toString().equals(riddles.getFunnyRiddlesAnswerByPos(randomRiddle))) {
passedQuestions.add(randomRiddle);
do {
if (clickCounter <= passedQuestions.size()) {
randomRiddle = rnd.nextInt(riddles.getFunnyRiddles().length);
clickCounter++;
} else {
Toast.makeText(getActivity().getApplication(),
"No more riddles!", Toast.LENGTH_SHORT).show();
//clickCounter++;
break;
}
} while (passedQuestions.contains(randomRiddle));

TextView text = (TextView) getActivity().findViewById(R.id.txtAnimalRiddle);
text.setText(riddles.getFunnyRiddlesByPos(randomRiddle));
/*Toast.makeText(getActivity().getApplication(),
riddles.getFunnyRiddlesByPos(randomRiddle), Toast.LENGTH_SHORT).show();*/
} else {
Toast.makeText(getActivity().getApplication(),
"Wrong answer!", Toast.LENGTH_SHORT).show();
}
}
});


Now every 1-2 clicks the toast saying
no mo riddles
shows up. It is supposed to be shown when there are no more unique values left.
I know that I'm missing some logic here, but I can't spot the right way to do it. The above code may be a useless crap, but this is what I came so far.

Answer

If I understand your question correctly, you want to show the riddles in a random order. But what you're doing is showing four random riddles from the list, which is likely to result in at least one of the riddles being shown more than once.

If this interpretation is correct, the easiest solution is probably to generate a random permutation of the array of riddles, then display them in that order.