Help needed filling array with unique random numbers

Please support our C++ advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Dec 2008
Posts: 1
Reputation: kitf84 is an unknown quantity at this point 
Solved Threads: 0
kitf84 kitf84 is offline Offline
Newbie Poster

Re: Help needed filling array with unique random numbers

 
0
  #31
Dec 1st, 2008
Originally Posted by bling_bling_vr6 View Post
Hello, I need some help filling an array with UNIQUE random numbers. So far I've figured out how to fill an array with random numbers, that's easy, but I'm stuck on how to avoid filling it with duplicate values. I'm assuming that i'll have to use either a linear or binary search function while filling the array, but my attempts so far have failed. Anyone got any idea what i'm doing wrong? Here's my terrible code so far...any help would dearly be appreciated.

I recently had a situation where I had to choose 10 random questions out of a bank of 30. The questions should be unique. There are probably more efficient ways of doing this and there is the potential for an infinite loop (or at least a really long one)

  1. //Pick 10 unique random questions out of a bank of 30
  2. int currentRandInt;
  3. questionNumbers[0] = getRandInt(0,29); //First one's free
  4. for (int i = 1; i < 10; i++)
  5. {
  6. currentRandInt = getRandInt(0,29); //Get a rand int
  7.  
  8. //Check this rand int against all previous stored values
  9. for int (j = 0; j < i; j++)
  10. {
  11. if(currentRandInt == questionNumbers[i])
  12. {
  13. //If we have a match, get a new rand int and begin again
  14. currentRandInt = getRandInt(0,29);
  15. j = 0; //Here's where the potential for infinite loop is introduced
  16. }
  17. }
  18. //If this is a unique rand int then keep it and proceed to to the next value
  19. questionNumbers[i] = currentRandInt;
  20. }

Substitute in your own random int function, but the logic should be similar.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the C++ Forum


Views: 10515 | Replies: 30
Thread Tools Search this Thread



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

©2003 - 2009 DaniWeb® LLC