vendredi 3 novembre 2017

Random Number Occurance Check

I have an array of Strings and when the user taps the button inside my app I generate a random number and use it to select a random String from my facts[] array. However, I tried improving my code so that the same random number would "never" occur(leading to the same String been shown to the user). Despite my efforts, my "Check" blocks doesn't seem to work since it generates a random fact when I click the button for the first time and then it does nothing. Please help me figure out the correct logic behind this and maybe write a more efficient code-block.

My current logic: check if the random number that has been generated already exists in my int[] factsCheck array and if it does create another one.If it doesn't add it to the array so that the program knows it has already been created once.

    int[] factsCheck = new int[facts.length];
boolean isNotNewRandomNumber = true;
int count = 0;
int randomNumberToReturn;

private void initFactsCheck() {
    for(int i=0; i<=factsCheck.length;i++) {
        factsCheck[i] = -1;
    }
}

String getFact() {
    // Randomly select a fact
    Random randomGenerator = new Random();
    while(isNotNewRandomNumber) {
         randomNumberToReturn = randomGenerator.nextInt(facts.length);
        for(int i = 0; i<factsCheck.length; i++) {
            if(factsCheck[i] == randomNumberToReturn) {
                break;
            } else {
                count++;
            }
        }
        if (count == factsCheck.length) {
            // Doesn't exist
            isNotNewRandomNumber = false;
        }
        count = 0;
    }
    return facts[randomNumberToReturn];
}




Aucun commentaire:

Enregistrer un commentaire