C # random pair generation

Suppose the possible outcome of an abandoned stamp is one of {1,2,3,4,5,6}

When two bones are selected three times , I want to collect random results from two bones.

My implementation

var q = from threeTimes in new int[] { 1, 2, 3 }
                    let set1 = new Random().Next(1, 6)
                    let set2 = new Random().Next(1, 6)
                    select new { s1 = set1, s2 = set2 };

            foreach (var v in q)
            {
                Console.WriteLine("Die1 :{0} Die2 :{1}", v.s1, v.s2);
            }

But most of the time I get the same values ​​for Die1 and Die2.

I mean

Die1: 5   Die2:  5

Die1: 2   Die2:  2

Die1: 2   Die2:  2

What correction do I need to make in order to get random pairs?

+3
source share
5 answers

This is because you create two objects Randomefficiently instantly. By default, they are seeded using a time value, most likely Environment.TickCount, although I have not seen this confirmed.

Random , , :

var rnd = new Random();
var q = from threeTimes in new int[] { 1, 2, 3 }
        let set1 = rnd.Next(1, 6)
        let set2 = rnd.Next(1, 6)
        select new { s1 = set1, s2 = set2 };
+11

( ) , .

+3

Random(), .Next():

Random random = new Random();
var q = from threeTimes in new int[] { 1, 2, 3 }
                    let set1 = random.Next(1, 6)
                    let set2 = random.Next(1, 6)
                    select new { s1 = set1, s2 = set2 };

            foreach (var v in q)
            {
                Console.WriteLine("Dice1 :{0} Dice2 :{1}", v.s1, v.s2);
            }
+2

random.Next(); ?

, , . Random .

r = Random(); set1 = r.next(1,6); set2 = r.next(1,6);

0

Bart de Smet , , .

0

Source: https://habr.com/ru/post/1724474/


All Articles