生成相同的随机数
本文关键字:随机数 | 更新日期: 2023-09-27 18:01:30
private int left;
private int middle;
private int right;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Random r = new Random();
left = r.Next(1, 4);
middle = r.Next(1, 4);
right = r.Next(1, 4);
while (left == middle)
{
left = r.Next(1, 4);
middle = r.Next(1, 4);
}
while (left == right)
{
left = r.Next(1, 4);
right = r.Next(1, 4);
}
while (middle == left)
{
middle = r.Next(1, 4);
left = r.Next(1, 4);
}
while (middle == right)
{
middle = r.Next(1, 4);
right = r.Next(1, 4);
}
while (right == left)
{
right = r.Next(1, 4);
left = r.Next(1, 4);
}
while(right == middle)
{
right = r.Next(1, 4);
middle = r.Next(1, 4);
}
}
到目前为止,这是我所拥有的,但我不希望这三个变量具有相同的数字,我认为while循环会解决这个问题,但它没有。我还是c#新手,有人有什么建议吗?
这样做可能更容易:
var r = new Random();
var numbers = new List<int> { 1, 2, 3 }.OrderBy(n => r.Next()).ToList();
left = numbers[0];
middle = numbers[1];
right = numbers[2];
这将打乱你想要的数字,然后你可以将它们分配给你的三个变量。它还保证不会永远循环,因为您知道您的值已经是唯一的。
你想让数字1、2和3以某种随机顺序排列吗?一种解决方案是创建一个列表,并以随机顺序提取项目。下面是一个简单的例子:
Random r = new Random();
var numbers = new List<int> { 1, 2, 3 };
left = TakeRandom(numbers, r);
middle = TakeRandom(numbers, r);
right = numbers[0];
...
private static int TakeRandom(List<int> list, Random r)
{
var index = r.Next(0, list.Count);
var result = list[index];
list.RemoveAt(index);
return result;
}
当然,可能有更优雅的方式来写它(我想到了扩展方法),但我认为这已经传达了重点。
使用这个循环来确保这三个都是不同的
while (left == middle || middle == right || right == left) {
left = r.Next(1,4);
middle = r.Next(1,4);
right = r.Next(1,4);
}
你为什么不试试呢?
Random r = new Random();
left = r.Next(1,4), middle = r.Next(1,4), right = r.Next(1,4);
while ( left == middle || middle == right || left == right){
left = r.Next(1,4); middle = r.Next(1,4); right = r.Next(1,4);
}
——或
Random r = new Random();
left = r.Next(1,4); middle = r.Next(1,4); right = r.Next(1,4);
while ( left == middle ){
middle = r.Next(1,4);
}
while (left == right || middle == right){
right = r.Next(1,4);
}