Same numbers in randomized array

Please support our C# advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Jan 2009
Posts: 3
Reputation: kaczmar86 is an unknown quantity at this point 
Solved Threads: 0
kaczmar86 kaczmar86 is offline Offline
Newbie Poster

Same numbers in randomized array

 
0
  #1
Jan 14th, 2009
I have function which randomizes numbers:
  1. public int losuj()
  2. {
  3. Random losowanie = new Random();
  4. int los = losowanie.Next(0, 9);
  5. return los;
  6. }
I want to fill array with numbers generated by losuj function, so I wrote:
  1. for (int i = 0; i < 9; i++)
  2. for (int j = 0; j < 9; j++)
  3. planszaTab[i, j] = losuj();
Instead of array with random numbers all I get is array fill with the same number ex. 3. Each time I run program I get different number in which array is filled.

What I do wrong?
Last edited by kaczmar86; Jan 14th, 2009 at 6:24 am.
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 1,735
Reputation: LizR has a spectacular aura about LizR has a spectacular aura about 
Solved Threads: 186
LizR LizR is offline Offline
Posting Virtuoso

Re: Same numbers in randomized array

 
0
  #2
Jan 14th, 2009
Because its happening so fast the seed is the same for all.
move the
  1. Random losowanie = new Random();
to outside the function so its not recreated each time, so its a private variable to your class. You should get different numbers then.
Did I just hear "You gotta help us, Doc. We've tried nothin' and we're all out of ideas" ? Is this you? Dont let this be you! I will put in as much effort as you seem to.
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 2,054
Reputation: ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of ddanbe has much to be proud of 
Solved Threads: 311
ddanbe's Avatar
ddanbe ddanbe is offline Offline
Postaholic

Re: Same numbers in randomized array

 
0
  #3
Jan 14th, 2009
You want random numbers in the range from 0 to 9. Which is 10 possible outcomes.
The array in the for loops goes from 0 to 8, which is 9 places.
If that is what you want, OK with me. But I like to mention it anyway.
Today is a gift, that's why it is called "The Present".
Make love, no war. Cave ab homine unius libri.
Danny
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:




Views: 585 | Replies: 2
Thread Tools Search this Thread



Tag cloud for C#
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC