我剛剛在 C# 和 WinForms 中開始了我的第一個小專案,我在這個功能上停留了幾天。
我有一個包含大約 60 個圖片框的陣列,當我按下一個按鈕時,我希望它從中隨機選擇一個,但不是連續兩次。
我想我正在尋找類似的東西:
static Random rnd = new Random();
int lastPick;
if (checkBox1.Checked == true)
{
int RandomPick = rnd.Next(pictureBoxArray.Length);
lastPick = RandomPick;
PictureBox picBox = pictureBoxArray[RandomPick **- lastPick**];
picBox.BorderStyle = BorderStyle.FixedSingle;
}
我還嘗試創建一個包含我最后一個 Pick 的串列并嘗試使用它,但它也沒有作業,它給了我一個超出范圍的例外。
static Random rnd = new Random();
int lastPick;
List<int> lastNumber = new List<int>();
if (checkBox1.Checked == true)
{
int RandomPick = rnd.Next(pictureBoxArray.Length);
lastPick = RandomPick;
lastNumber.Add(lastPick);
PictureBox picBox = pictureBoxArray[RandomPick - lastNumber.Count];
picBox.BorderStyle = BorderStyle.FixedSingle;
}
任何幫助或提示進入正確方向將不勝感激
uj5u.com熱心網友回復:
我覺得你把問題復雜化了。您可以簡單地將最新索引存盤在變數中(就像您正在做的那樣),然后生成一個亂數,直到它與變數中的索引不同。這是一個示例代碼片段:
int lastPick;
while (true) {
int randomPick = rnd.Next(length);
if (randomPick != lastPick) {
lastPick = randomPick;
// Do things here.
break; // This breaks the loop.
}
// If the previous if-statement was false, we ended
// up with the same number, so this loop will run again
// and try a new number
}
uj5u.com熱心網友回復:
你很接近,只是隨機選擇,直到新的選擇與之前的不一樣。
int lastPick = -1;
int randomPick = -1;
if (checkBox1.Checked == true)
{
while (randomPick == lastPick)
{
randomPick = rnd.Next(pictureBoxArray.Length);
}
lastPick = randomPick;
PictureBox picBox = pictureBoxArray[randomPick];
picBox.BorderStyle = BorderStyle.FixedSingle;
}
uj5u.com熱心網友回復:
由于其他答案使用 while 回圈,我想提出一種無需 while 回圈的方法。創建一個已初始化的索引串列,以包含陣列中所有可能的索引。此解決方案需要System.Linq
.
將您之前選擇的索引初始化為 -1。
int lastChosenIndex = -1;
在陣列中創建所有可能索引的串列。
List<int> indicesList = Enumerable.Range(0, pictureBoxArray.Length).ToList();
現在,當您想要陣列中的索引時,您可以從索引串列中獲取索引。
var randomIndex = random.Next(indicesList.Count - 1);
var randomItem = pictureBoxArray[indicesList[randomIndex]];
我們將從索引串列中洗掉這個選擇的索引,這樣就不能再次選擇它。首先,我們需要重新添加之前洗掉的索引(如果它不是 -1),因為它現在是一個有效的選擇。
if (lastChosenIndex > -1)
// Use Add so the index into this list doesn't change position
indicesList.Add(lastChosenIndex);
lastChosenIndex = indicesList[randomIndex];
// by removing the index at this position, there is no way to choose it a second time
indicesList.RemoveAt(randomIndex);
好訊息是,如果您不想顯示重復,您可以洗掉最后選擇的索引代碼,它永遠不會顯示重復。與其他答案相比,這有點冗長,但想表明有一種替代方法可以在 while 回圈中使用蠻力。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473546.html