vendredi 13 décembre 2019

Check if int[] contains an int

For some reason, my script is making an infinite loop, I think, and I cannot figure out why. I have an array with 40 pawns and need to put these randomly on a board. So I have a random number that choose a random pawn from the array, but if the pawn has already been chose, it has to pick a new random number, but that last part seems to bug for some reason. And i cannot figure out why.

Random rand = new Random();    

    int[] availablePawnsArray = {1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 11, 12, 12, 12, 12, 12, 12 };
    // this array contains 40 integers

    int[] chosenPawns = new int[40];
    //this array contains the index numbers of already selected pawnsfrom the previous array

    int counter = 0;
    //counts how many pawns have been selected already    

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 10; j++) {
        //this refers to my board, 40 locations for my 40 pawns    

            int chosenPawn = rand.nextInt(40);
            //a random numder from 0 to 40

            boolean found = false;
            //a boolean to say if i have already selected this pawn before or not    

            do {
               for (int n : chosenPawns) {
                   if (n == chosenPawn) {
                       found = true;
                       chosenPawn = rand.nextInt(40);
                   } else {
                       found = false;
                   }
               }
            } while(found == true);    

            board[i][j].rank = availablePawnsArray[chosenPawn];
            chosenPawns[counter] = chosenPawn;
            counter++;
        }
    }



Aucun commentaire:

Enregistrer un commentaire