Aug 27, 2008 at 9:59pm UTC
Hi,
I am wondering if you can ,after making a random number, take away that number from the random generator so you won't get it again the next time you make a random number. I am using srand.
For example: x=rand()%10+1 //say for example this makes x = 3
when I do this again I want it to not make another 3.
Thank you in advance!
Last edited on Aug 27, 2008 at 10:11pm UTC
Aug 27, 2008 at 10:11pm UTC
Not in the way you are thinking.
But lets say you wanted to draw a lottery, numbers 1-10. Each number can only appear once. You'd do.
1 2 3 4 5 6 7 8 9 10 11 12 13
vector<int > vBallList;
for (int i = 0; i < 10; ++i)
vBallList.push_back( (i+1) ); // numbers 1-10.
srand(time(NULL));
for (int i = 0; i < 10; ++i) {
int no = rand() % (10-i);
cout << "Number was: " << vBallList[no] << endl;
// Remove Picked Number
vBallList.erase (vBallList.begin()+no);
}
Haven't tested, or compiled that code. So take is as pseudo-code. Thats the theory of how I'd do it.
Edit: Whoa. It worked first time lol. Scary
Last edited on Aug 27, 2008 at 10:13pm UTC
Aug 27, 2008 at 10:55pm UTC
It worked!
Thank you, Zaita!
This also taught me what vectors were and how to use them.
Aug 27, 2008 at 11:45pm UTC
No worries :)
Vectors are good to know, just good C++ STL if you wanna learn them better.
Aug 28, 2008 at 12:01am UTC
Yeah, I was trying to do it with an array (which I eventually got it to work) ,but using vectors was so much easier.