chility chility - 1 year ago 56
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(
), But I would like to stop generating randoms when I have shown all the values of the
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() {
public void onClick(View view) {
if (txtAnswer.getText().toString().equals(riddles.getFunnyRiddlesAnswerByPos(randomRiddle))) {
do {
if (clickCounter <= passedQuestions.size()) {
randomRiddle = rnd.nextInt(riddles.getFunnyRiddles().length);
} else {
"No more riddles!", Toast.LENGTH_SHORT).show();
} while (passedQuestions.contains(randomRiddle));

TextView text = (TextView) getActivity().findViewById(;
riddles.getFunnyRiddlesByPos(randomRiddle), Toast.LENGTH_SHORT).show();*/
} else {
"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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download