| | |
Help needed filling array with unique random numbers
Please support our C++ advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
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: 10515 | Replies: 30
| Thread Tools | Search this Thread |
Tag cloud for C++
6 add api array arrays beginner binary bitmap c++ c/c++ calculator char class classes code compile compiler console conversion convert count data delete desktop directshow dll encryption error file forms fstream function functions game getline givemetehcodez google graph homeworkhelper iamthwee ifstream input int integer java lazy lib linkedlist linux loop looping loops map math matrix memory microsoft newbie news node number output parameter pointer problem program programming project proxy python random read recursion recursive reference return sort string strings struct studio system template templates test text tree unix url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets





