mardi 22 août 2017

Random number generator generates duplicates

Framework: Java

public static List<Integer> buttonIdList = new ArrayList();

public void myMainMethod() {
   for(Integer i = 0; i < 11; i++) {
      int randomButtonId = getUniqueIdNumber();
   }
}

private static Integer getUniqueIdNumber() {
        Random ran = new Random();
        int randomButtonId = ran.nextInt(20) + 1;

        if(buttonIdList.contains(randomButtonId)) {
            getUniqueIdNumber();
        } else {
            buttonIdList.add(randomButtonId);
        }

        return randomButtonId;
    }

When the code encounters a duplicate, it calls itself (recursively) and in the second try if the number is unique the return statement returns it to the myMainMethod or to getUniqueIdNUmber?

Where should the return statement be placed?




Aucun commentaire:

Enregistrer un commentaire