[英]Generating random number and avoid duplicated value
我現在嘗試:1.隨機生成四個數字。 2.將它們存儲在數組中。 3.確保數組中的值不重復。
這是我的想法:1.每次在for循環中生成一個數字(x4次)2.生成數字后,使用內部循環將其與先前的數組值進行比較。
我的代碼:
do
{
for (int i = 0; i < 4; i++)
{
value[i] = rand() % 6 + 1; // Generating value
for (int j = 0; i > j; j++)
{
if (value[i] == value[j])
{
dup = true; break;
}
if (dup == true) break;
}
}
for (int i = 0; i < 4; i++)
{
cout << "value: " << value[i] << " " << endl;
}
} while (dup != true);
我想知道為什么仍然會生成相同的數組值,就像在我的代碼中一樣,循環將重復進行,直到找不到更多重復的值為止。
關於為什么得到重復結果的原因,是因為您正在繼續嘗試while (dup != true)
。 請仔細閱讀:如果沒有重復的內容,請繼續嘗試。
這意味着它會不斷嘗試,直到有一個重復。
在任何情況下, 通常都可以使用Fisher Yates混洗來最好地解決此類問題,但是,對於這樣小的搜索空間(六個搜索中的四個),您可以避免使用該方案。
但是,最好將每個數字與之前的每個數字進行比較,如下所示:
def getFourFromSix():
num = []
num.append (random(1..6))
num.append (num[0])
while num[1] == num[0]:
num[1] = random(1..6)
num.append (num[0])
while num[2] == num[0] or num[2] == num[1]:
num[2] = random(1..6)
num.append (num[0])
while num[3] == num[0] or num[3] == num[1] or num[3] == num[2]:
num[3] = random(1..6)
return num
這樣,您實際上並不需要一路返回並在每次找到重復項時都重新啟動,只需要重試一次當前的號碼即可。
如果您確實希望Fisher Fisher進行洗牌(如果數字池變大,它會稍微優雅一點),則M-from-N變體很簡單:
def getMFromN(m, n):
# Sanity checking.
if m > n:
throw "Trying to extract too many things"
num = []
# Populate choices that we will select from.
for index in 0..n-1:
choice[index] = index + 1
# For each desired number.
for index in 0..m:
# Copy from choices to results.
choose = random(0..n-1)
num.append (choice[choose])
# Remove from results so no repeats.
n = n - 1
choice[choose] = choice[n]
return num
您的代碼中存在邏輯缺陷。 到循環中斷時,您已經將rand生成的重復值存儲到“值”數組中。 您將不得不重新處理索引,直到沒有重復為止-或-使用更好的數據結構。
為什么不使用set<int>
這樣它將僅包含唯一值,並且在填充N個唯一元素時可以退出/中斷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.