检查重复随机输出的更有效方法?
More efficient way of checking for a duplicate random output?
尝试使用随机函数更改某些按钮的位置,我目前对我的每个按钮使用 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);
此类任务的常用解决方案是使用 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]
这是@gurustron 的另一种变体。此解决方案使用 Random
对值
进行排序
var rnd = new Random();
var indexes = Enumerable.Range(0, 3).OrderBy(_ => rnd.Next(1000)).ToArray();
尝试使用随机函数更改某些按钮的位置,我目前对我的每个按钮使用 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);
此类任务的常用解决方案是使用 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]
这是@gurustron Random
对值
var rnd = new Random();
var indexes = Enumerable.Range(0, 3).OrderBy(_ => rnd.Next(1000)).ToArray();