I'm making a game and i have 20 events.I want to them to occur 5 timses ( 5 events ) and what they would all be random.For events I'm using if ( if random number is x ) , and a function after that random number.
I can make them appear , but sometimes couple of them are the same.
Basically you want to chose 5 events out of 20 with no duplicates, yes?
You need to use a do-while loop which calls rand() until you get a number you haven't gotten before. So you will need to store the number you've already chosen in either a C-style array (or a standard container, if you're familiar with them) so you can check whether or not a random number has been used.
Thanks again, but from that i couldnt understand it really.
One guy told me what if i'm not capable of thinking this myself,i shouldn't be programming at all.Hope i find the answer :D
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
usingnamespace std ;
constint NEVENTS = 20 ;
constint NRANDOMLY_CHOSEN = 5 ;
// create a sequence of NEVENTS events 0, 1, 2 ... NEVENTS-1
int events[NEVENTS] ;
for( int i = 0 ; i < NEVENTS ; ++i ) events[i] = i ;
srand( time(0) ) ;
cout << "the randomly chosen event numbers are: " ;
for( int i = 0 ; i < NRANDOMLY_CHOSEN ; ++i )
{
// choose a random position from the remaining (NEVENTS-i) events starting at position i
// (the events at positions 0, 1, ... (i-1) have been chosen earlier)
constint chosen_pos = i + rand() % (NEVENTS-i) ;
// swap the randomly chosen event with the event at position i
int temp = events[i] ;
events[i] = events[chosen_pos] ;
events[chosen_pos] = temp ;
cout << events[i] << ' ' ; // print out the chosen event
}
cout << '\n' ;
}
THese two libraries do not provide any random number generating capabilities.
So if you want to use only those two libraries, you need to either forget about random numbers, or write random number generator yourself.