mercredi 3 octobre 2018

Not able to randomize two numbers to be different and not present in an array

My current code is:

     int[] usedRVals = new int[8];
     int[] usedCVals = new int[8];
     Arrays.fill(usedRVals, 99);
     Arrays.fill(usedCVals, 99);



        for (int l = 0; l < 8; l++) {
        r = 0;
        c = 0;
        // get new random numbers that aren't the same
        while (r == c && !Arrays.asList(usedRVals).contains(r) && !Arrays.asList(usedCVals).contains(c)) {
            r = randomNum();
            c = randomNum();
        }
        usedRVals[l] = r;
        usedCVals[l] = c;
   }


 private static int randomNum() {

        Random r = new Random();
        return r.nextInt(8);

    }

I'm attemping to get a new number (between 0 and 7) that hasn't been used before in the same loop, but I'm unable to find the logic error in my code. Any help would be appriciated.




Aucun commentaire:

Enregistrer un commentaire