我有一个包含 40 个整数值的整数数组,需要将它们随机放入另一个整数数组中。
我有一个随机数,它从第一个数组中选择一个随机值,但如果已经选择了该特定整数,则它必须选择一个新的随机值,但最后一部分似乎由于某种原因而出现错误。
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++;
}
}
最佳答案
除非您需要将其实现为练习,否则您可以使用内置的 shuffle
方法,将可用 pawn 数组包装在列表中:
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];
关于java - 如何用Java中另一个整数数组中的值随机填充ant int数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59323313/