嘗試使用隨機函式更改某些按鈕的位置,我目前為每個按鈕使用 3 個 while 回圈設定。它有效,但我想知道是否有更有效的方法來防止隨機輸出與我所擁有的相同?(我對編程很陌生,所以請告訴我如何改進。謝謝!!:D)
Random r = new Random();
int location = r.Next(0, 3);
btnCorrect.Location = new Point(xCoordinates[location], positionY);
int location2 = r.Next(0, 3);
while (location2 == location)
{
location2 = r.Next(0, 3);
}
btnIncorrect1.Location = new Point(xCoordinates[location2], positionY);
int location3 = r.Next(0, 3);
while (location3 == location|| location3==location2)
{
location2 = r.Next(0, 3);
}
btnIncorrect2.Location = new Point(xCoordinates[location2], positionY);
uj5u.com熱心網友回復:
此類任務的常用解決方案是使用Fisher-Yates shuffle。在你的情況下,你可以洗牌索引:
var rnd = new Random();
var indexes = Enumerable.Range(0, 3).ToArray();
for (int i = 0; i < indexes.Length; i )
{
var j = i rnd.Next(indexes.Length - i);
var element = indexes[i];
indexes[i] = indexes[j];
indexes[j] = element;
}
// use indexes to select elements
// i.e. location = indexes[0], location1 = indexes[1], location2 = indexes[2]
uj5u.com熱心網友回復:
這是@gurustron答案的另一種變體。此解決方案Random用于對值進行排序
var rnd = new Random();
var indexes = Enumerable.Range(0, 3).OrderBy(_ => rnd.Next(1000)).ToArray();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/315636.html
