生成相同的随机数

时间:2014-05-02 21:07:36

标签: c# random

    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#有没有人有任何建议?

4 个答案:

答案 0 :(得分:4)

这样做可能更容易:

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 :(得分:0)

使用此循环来确保所有3个不同

while (left == middle || middle == right || right == left) {
    left = r.Next(1,4);
    middle = r.Next(1,4);
    right = r.Next(1,4);
}

答案 2 :(得分:0)

所以你想要一些随机顺序的数字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;
}

当然,可能有更优雅的方式来编写这个(扩展方法浮现在脑海中),但我认为这可以解决问题。

答案 3 :(得分:-2)

为什么不试一试?

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);
}