Wednesday, 15 May 2013

linq - C# Random Pair generation -


Assume that the possible death consequences are {1,2,3,4,5,6}

When two dice is thrown thrice , I want to collect random results from two dice.

My implementation

  var q = 3 times in new int [] {1, 2, 3} set 1 = new random () Next (1, 6) set 2 = new random () Next (1, 6) select new {s1 = set1, s2 = set2}; Forchcha (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 the DI1 and DI2.

I mean

  Die1: 5 Die2: 5Diay 1: 2DAY 2: 2DAY 1: 2DAY 2: 2  
< P> What do I need to improve to get random pairs?

This is because you have two random items effectively By default, they are getting preference using a time-based value, most likely Environment.TickCount , although I have not confirmed this.

A Random will solve it before your query, because the two items must be sewed separately:

  var rnd = new Random ( ); Var q = 3 times in new int [] {1, 2, 3} set 1 = rnd. Next (1, 6) set 2 = rnd. Select Next (1, 6) New {s1 = set1, s2 = set2};  

No comments:

Post a Comment