Alex
Alex

Reputation: 1420

How to make a int not be used twice when it randomly generates them?

I've coded a simple quiz game for Android, and currently Im having troubles with making questions not appear after they've been shown, i.o. I dont want it to ask me the same question twice..

This is the method Im using

 private void QBegin() {
   /*
    * Gets a random question
    */
    question = (TextView) findViewById(R.id.question);
    String[] types = { "Question one",
            "Question two", 
            "Question three", 
            "Question four",
            "Question five"};
    Random random = new Random();
    int qType = random.nextInt(types.length);
    question.setText(types[qType]);
    getAnswers(qType); //gets four answers
}

Im not sure if this will work but, what if I add something like

Edit : Doesn't work..

    int i = 0;
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(qType);
    i++;
    if(list.contains(qType) && i != types.length + 1){
        return;
    } else {
        answerCounter.setText("Hit the bricks pal, you're done..");
    }

Edit 2: Got told to add something like this, but I have NO IDEA what I should be doing with this now..

    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(types.length);
    Collections.shuffle(list);
    if(!list.contains(qType)){
        // help please, as I have no idea on what I should be doing!
    }

Upvotes: 0

Views: 829

Answers (2)

mishadoff
mishadoff

Reputation: 10789

Simple algorithm below:

You need generate value from 0 to N without repeatings.

  1. Define an array with those elements [0..N] (array[n])
  2. Generate random number in interval [0..N] (rand)
  3. Choose in array element, where generated value is index (array[rand])
  4. Swap these element with the last in array (swap array[rand] <-> array[N])
  5. Next time you generate index in [0..N-1] so in that case previously generated element won't be selected.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502406

The simplest approach would be to generate an ArrayList of all the possible numbers you want to use, the shuffle them with Collection.shuffle. Then just iterate over the list.

EDIT: Your question is really unclear now, given that you've said you don't want the questions in a random order... whereas your sample code appears to be trying to present the questions in a random order. Anyway... here's what I was suggesting:

List<Integer> indexes = new ArrayList<Integer>();
for (int i = 0; i < types.length; i++) {
     indexes.add(i);
}
Collections.shuffle(indexes);

for (Integer index : indexes) {
    question.setText(types[index]);
    getAnswers(index);
    // Now do something else? It's unclear...
}

Upvotes: 6

Related Questions