gpt4 book ai didi

java - java中如何删除二维数组中的重复项?

转载 作者:行者123 更新时间:2023-12-02 07:52:53 24 4
gpt4 key购买 nike

我正在尝试通过 2D 数组生成数独板:board[5][5]。数独板应该只包含独特的元音。然而,我只是让独特的元音连续出现。对于列,它们似乎仍然有重复项。我该如何使用迄今为止的代码生成一个没有重复项的列?

这是我用于连续生成唯一字母的代码:

String [] vowels = {"A","E","I","O","U"};
String [][] board = new String [vowels.length][5];

public Actions(){
int rows = 5;
for(int row = 0;row<rows;row++){
ArrayList<String> tempVowels = new ArrayList<String>(Arrays.asList(vowels));
int numVowPerLine = (int)Math.floor(Math.random()*4);
for(int j = 0;j<numVowPerLine;j++){
do{
int pos = (int)Math.floor(Math.random()*5);
if(board[row][pos] == null){
int temp = (int)Math.floor(Math.random()*tempVowels.size());
board[row][pos] = tempVowels.get(temp);
tempVowels.remove(temp);
break;
}
}while(true);
}

}

致谢:L7ColWinters

最佳答案

这与一个众所周知的问题有关,称为 Rooks Problem .

我可以建议一个更简单的循环吗?

编辑:阅读评论后,我发现问题需要应用于每个元音。在我看来,这更具可读性:

java.util.Random random = new Random();

boolean[] r_occupied;
boolean[] c_occupied;

for (i = 0; i < vowels.length; i++)
{
// Clear the 'occupied' information
r_occupied = new boolean[5];
c_occupied = new boolean[5];

// we will put vowel[i] 'count' times into the 'board'
count = random.nextInt(5);

for (j = 0; j < count; j++)
{
// generate a random row
row = random.nextInt(5);

// if it is already occupied, select the next one
while (r_occupied[row])
row = (row + 1) % 5;

// generate a random column
col = random.nextInt(5);

// if it is already occupied, select the next one
while (c_occupied[col])
col = (col + 1) % 5;

/* put the vowel at board[row][col] */
r_occupied[row] = true;
c_occupied[col] = true;
board[row][col] = vowel[i];
}
}

注意:它会覆盖一些元音,但这应该没问题。

关于java - java中如何删除二维数组中的重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10007872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com