-1

I was working on a quiz app in Android studio..

  • I have 2 tables which are the solutions and questions..
  • In my game, I wanna create a random number in the range of this table without duplicates..
  • with this random number I update my questions and answers..

I try this code now to create numbers (with duplicates):

Random rand = new Random();

n = rand.nextInt(QuestionLibrary.mChoices.length) + 1;

here is the photo of my game

enter image description here

thlpswm
  • 45
  • 3
Marios
  • 5
  • 7

1 Answers1

0

If you don't have much numbers, you can make a collection with all of them, shuffle and then take one by one from it. If you have a lot of numbers, then better aproach would be to make an empty collection and add every number that random function returns if it already does not exists. If number already exists, get another one, and so on.

Please read more here: https://stackoverflow.com/a/4040014/7270175

EDIT: added code snippet that reproduces MAX number of different random numbers without duplicates.

private static int MAX = 1000;
private static boolean[] numbers;

public static void main(String[] args) {

    Random generator = new Random();
    numbers = new boolean[MAX + 1];

    for (int i = 0; i < MAX; i++) {
        System.out.println(getRandomWithoutDuplicates(generator));
    }
}

private static int getRandomWithoutDuplicates(Random generator) {
    int randomNum;
    do {
        randomNum = generator.nextInt(MAX);
    } while (numbers[randomNum]);
    numbers[randomNum] = true;
    return randomNum;
}
Matej Vukosav
  • 666
  • 8
  • 12