[英]How can I avoid duplicates when generating a random list of pairs of numbers?
[英]Method for avoiding duplicates when generating a random list of pairs of numbers is not working as it should
我有以下代碼,用於在boolean [] []中將隨機值設置為true,而不重復:
int a = 0;
int b = 0;
int counter = 0;
for (int i=0; i<=50; i++) {
do {
a = randomizer.nextInt(hoogte);
b = randomizer.nextInt(breedte);
/**debug variable*/
counter++;
} while (bommaker[a][b]);
bommaker[a][b] = true;
}
經過一段時間的測試,我發現出了點問題,因此我添加了一個計數器來檢查它。 每次我運行該程序時,“計數器”中都會出現一個不同的數字。 一次是57,而另一次是63。但是我將循環設置為正好51。這意味着代碼無法正常工作。 有人可以解釋為什么它生成超過51個數字並給出可能的解決方案嗎?
您必須記住,循環中有一個循環。 OUTTER循環最多只能執行51次,但是內部循環將導致隨機的迭代次數(每次看到數組已設置為true時,都會進行一次額外的迭代)。
除了計數器的值大於您的預期之外,代碼不起作用怎么辦?
從do while循環中移出counter ++行
int a = 0;
int b = 0;
int counter = 0;
for (int i=0; i<=50; i++) {
do {
a = randomizer.nextInt(hoogte);
b = randomizer.nextInt(breedte);
/**debug variable*/
} while (bommaker[a][b]);
counter++;
bommaker[a][b] = true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.