Skip to content
Advertisement

How to fill ant int array randomly with values from another integer array in Java?

I have an integer array with 40 integer values and need to put these randomly on into another integer array.

I have a random number that chooses a random value from the first array, but if that specific integer has already been chosen, it has to pick a new random value, but that last part seems to bug for some reason.

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++;
    }
}

Advertisement

Answer

Unless you need to implement it as an exercise you could use the built in shuffle method, wrapping your array of available pawns in a list:

Collections.shuffle(Arrays.asList(availablePawnsArray));
    
for (int i = 0, k = 0; i < 4; i++) 
    for (int j = 0; j < 10; j++, k++) 
        board[i][j].rank = availablePawnsArray[k];
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement