# My C++ Homework...Simple Question

• 02-08-2006
tineras
My C++ Homework...Simple Question
I need to draw 8 random numbers (from 1 to 4). The numbers can only repeat once. I need there to be two 1s, two 2s, two 3s, and two 4s in random order. I need them put into an array.

Example Output: 1,3,4,2,4,1,3,2 or 3,1,1,4,3,2,2,4 (I'm sure you get the idea!)

It would now equal:

Code:

`intNumbers[8] = {1,3,4,2,4,1,3,2};`
This is a small piece of a bigger project, so I not just on here asking for answers. I really need help with this one. I've been staring at the same 10 lines for several hours now.

Thanks in advance for any help!
Tin
• 02-08-2006
7stud
You can put 1,1,2,2,3,3,4,4 into a <vector> and then call random_shuffle() on the vector. You can then copy() the elements of the vector to your array, although you might consider using a <vector> instead of an array to start with--then you wouldn't need to copy the <vector> to the array.

random_shuffle() is in <algorithm>.
• 02-09-2006
Daved
If you have to use the C style array, random_shuffle will work with that also:

std::random_shuffle(intNumbers, intNumbers + 8);
• 02-09-2006
7stud
Quote:

Originally Posted by Daved
If you have to use the C style array, random_shuffle will work with that also:

std::random_shuffle(intNumbers, intNumbers + 8);

Darn it.
• 02-09-2006
tineras
Thanks a million. Worked like a charm!
• 02-09-2006
7stud
Just so you know, you need to use srand(time(0)) to seed rand(), which is used by random_shuffle(). Otherwise, you will get the exact same sequence every time you run your program--try it.

time() is in <ctime>
• 02-09-2006
tineras
Luckily I already had that in my code. If I didn't, I would've been stumped. Thanks again!
• 02-09-2006
ZuK
Quote:

Originally Posted by 7stud
Just so you know, you need to use srand(time(0)) to seed rand(), which is used by random_shuffle(). Otherwise, you will get the exact same sequence every time you run your program--try it.

The implementation of the STL that I use ( g++ ) dosen't make use of the normal rand(), srand() c-functions. It uses an internal random generator that cannot be seeded.
but it's simple to provide one if needed

Code:

```struct randomgenerator {   int operator()( int range ) {       static int seeded = 0;       if ( ! seeded ) {           srand( time(0));           ++seeded;       }       return rand() % range;   } };```
use it this way:
Code:

```    randomgenerator random;     random_shuffle( intNumbers, intNumbers + 8, random );```
Kurt
• 02-09-2006
7stud
functor! Functor! I see you!

struct? <shudder>
• 02-09-2006
ZuK
Quote:

Originally Posted by 7stud
functor! Functor! I see you!

struct? <shudder>

What's wrong with that struct. There is nothing to be hidden or protected ?
Kurt