| | |
Help needed filling array with unique random numbers
![]() |
•
•
Join Date: Dec 2008
Posts: 1
Reputation:
Solved Threads: 0
•
•
•
•
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)
C++ Syntax (Toggle Plain Text)
//Pick 10 unique random questions out of a bank of 30 int currentRandInt; questionNumbers[0] = getRandInt(0,29); //First one's free for (int i = 1; i < 10; i++) { currentRandInt = getRandInt(0,29); //Get a rand int //Check this rand int against all previous stored values for int (j = 0; j < i; j++) { if(currentRandInt == questionNumbers[i]) { //If we have a match, get a new rand int and begin again currentRandInt = getRandInt(0,29); j = 0; //Here's where the potential for infinite loop is introduced } } //If this is a unique rand int then keep it and proceed to to the next value questionNumbers[i] = currentRandInt; }
Substitute in your own random int function, but the logic should be similar.
![]() |
Similar Threads
Other Threads in the C++ Forum
- Previous Thread: virtual class with friend functions
- Next Thread: Simple Varifacation please
Views: 11784 | Replies: 30
| Thread Tools | Search this Thread |
Tag cloud for C++
6 algorithm array arrays assignment beginner binary c++ c++borland c/c++ calculator char class classes code compile compiler constructor conversion convert count delete dll dynamic encryption error file files filestream forms fstream function functions game givemetehcodez graph graphics gui homework iamthwee input int integer lazy linker list loop loops map math matrix member memory network newbie news number object objects opengl operator output parameter pointer pointers problem program programming project qt random read reading recursion recursive reference return server sort spoonfeeding string strings struct student studio template templates text time tree variable vc++ vector video visual win32 window windows winsock wxwidgets





