visual studio - When I declare Random inside my loop in C#, it gives me nonrandom numbers - declaring it outside my loop gives me random numbers. Why? -


this question has answer here:

i'm creating deck of cards. when try shuffle, getting weirdness.

the constructor before calling program goes through following loop (pseudo code,inclusive)-

for in (0,13):    j in (0,3):       new card(i,j) 

this simplified form,anyway. card number , suit generated. problem code (c#):

private void shuffle() {     list<card> newlist = new list<card>();     while (cards.count > 0)     {         random r = new random();         int next = r.next(0,cards.count);         console.writeline(next);         card cur = cards.elementat(next);         newlist.add(cur);         cards.remove(cur);     }     this.cards = newlist; } 

this gives me semi-predictable output - i.e. following:

18 18 18 17 17 17 16 16 15 15 15 14 14 14 13 13 13 12 12 12 11 11 11 10 10 10 9 9 9 8 8 8 7 7 7 6 6 6 5 5 5 4 4 3 3 3 1 5 4 3 2 2 1 0

near end seems break pattern, i'm not sure why. running again gives me different, non-random, outputs.

however, if remove random declaration outside loop -

    private void shuffle()     {         list<card> newlist = new list<card>();         random r = new random(); /** different line **/         while (cards.count > 0)         {             int next = r.next(0,cards.count);             console.writeline(next);             card cur = cards.elementat(next);             newlist.add(cur);             cards.remove(cur);         }         this.cards = newlist;     } 

i more random seeming numbers, in case -

19,28,21,2,16,20,33,26,7,36,31,33,33,26,34,4,18,20,13,27,16,11,18,22,18,21,21,8,22,12,6,17,2,17,0,11,2,14,9,0,8,10,1,7,4,1,0,0,2,1,0,0

this difference seems disappear when publish code visual studio , run outputted program. i'm confused what's going on. since have 4 cores, distributing process 4 cores @ same millisecond, thereby using same number seed? wouldn't make sense why it's working when publish code, though...

the random number generation starts seed value. if same seed used repeatedly, same series of numbers generated. 1 way produce different sequences make seed value time-dependent, thereby producing different series each new instance of random. default, parameterless constructor of random class uses system clock generate seed value,

by having declaration in loop calling constructor same value on , on again - hence getting same numbers out.

random class


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -