Random Number Generator with Container

The Objective : Creative any 3 Radnom Numbers between 0 -9 [withoutrepeat].In case of repeat,program should run again.
The problem: Yes,almost done.Sometime,the program create correct numbers.[ Ex: 8,4,2 ] but some time i get the numbers like -2,5,2. Here No -2 -repeat.

Since It is Random,I have to do some extra trick to AVOID the repeat
tried to check the output numbers for comparison but is still errors OR any BEST ALGORTHM to do this. Any suggestion, Welcome.

The Code:

class RndIntGen
RndIntGen(int l, int h)
: low(l), high(h)
{ }
int operator( )( ) const
return low + (rand( ) % ((high - low) + 1));
int low;
int high;

int main( )
srand(static_cast<unsigned int>(clock( )));
vector<int> v(3);
vector<int>::iterator it;
generate(v.begin(),v.end(),RndIntGen(1, 9));
// RndIntGen r1 = copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\n"));
copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\n"));
// while(v.begin()!=(v.end())) *v++ = RndIntGen();
// while(v.begin()!=(v.end())) *v++ = r1;
Make a container C containing the numbers 0-9 [10 elements total].
Make a loop that loops three times and does the following:
1. Randomly generate an index between 0 and #elements in C minus 1.
2. Read the element at that index from C and put the element into your vector V.
3. Remove the element from C.

V now contains three unique elements.

Another way:
Use std::set instead of vector.
Create an empty set S.
While the number of elements in S is less than three:
1. Randomly generate a number [0-9] inclusive.
2. Attempt to insert the number into S. It will fail if the number is already in the set.

Create a vector containing the sequence 0..9. Apply std::random_shuffle(). Pick the first three numbers.
Topic archived. No new replies allowed.