java - 如何用Java中另一个整数数组中的值随机填充ant int数组?

标签 java arrays random infinite-loop do-while

我有一个包含 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/

相关文章:

java - 如何调用 super 方法(即 : toString()) from outside a derived class

java - 如何在 ICEfaces 中选择上传文件的文件名?

python - numpy:按位和数组

c++ - 当某些元素有偏好值时选择随机元素

Java Spring Boot - 如何使用户能够从命令行切换数据文件?

java - 是否可以通过编程方式确定文件移动是否会产生副本?

c++ - c++中函数rand()使用的公式

mysql - 归档 5 小时从表中随机记录,并将权重设为 1/4

javascript - 在 JavaScript 函数式编程中如何使用 reduce 函数来查找一组数组之间的交集/联合?

javascript - JSON 处理 - JavaScript