If one array equals, generate next random and try again

Discussion in 'Plugin Development' started by Randy Schouten, Jun 26, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    Randy Schouten

    Basically exactly what the title says :p

    I have an array of numbers, and a random int generator.
    If even one array equals the current random number, get another random number and try again, then keep retrying until valid number is found.

    I know how to do this with one value, but not with multiple in an array.

    Thanks in advance
     
  2. Offline

    Connor Mahaffey

    Code:
    boolean tryAgain;
    int x;
    do{
        x = however you get the random number (Math.random(), Random class, etc.)
        tryAgain = false;
        for ( int i = 0; i < myArray.length; i++ ){
              if ( myArray[i] == x ){
                  tryAgain = true;
                  break;
              }
        }
    }while(tryAgain);
    
    x is your random number, myArray is your array. Get the random number first, and set tryAgain to false. Loop through the array, and if the number at a given spot equals the random number, set tryAgain to true and break out of the loop so it will loop again with a new random number. Otherwise exit the loop because no matches were found.

    Is this what you were asking?
     
  3. Offline

    Randy Schouten

    Works like a charm.
    And thank you for explaining it too!
     
  4. Offline

    Connor Mahaffey

    You're quite welcome!
     
Thread Status:
Not open for further replies.

Share This Page