# Problem creating unique random numbers

• 06-13-2010
jamort
Problem creating unique random numbers
I'm not sure whats wrong...

Code:

```#include <iostream> #include "math.h" #include "time.h" char *shapes[2] = {"ball", "cube"}; // two arrays for color and shape char *colors[4] = {"red", "blue", "orange", "green"}; int selectObject(int, int); //function prototype int main(){     int color = 0; //numbers to be used for selection and display     int shape = 0;                 int loopNumber;     for (loopNumber = 0; loopNumber <= 100; loopNumber++){         selectObject(color, shape);         std::cout<< colors[color]<< " "<< shapes[shape];     }         std::cin.get(); } int selectObject(int color, int shape){     std::srand(time(NULL)); // I thought this was to make each random number different?         color = std::rand() % 3; // gets random number to decide member of array to display     shape = std::rand() % 1;         return color;     return shape; }```
• 06-13-2010
Memloop
• 06-13-2010
EVOEx
1. Two return statements unconditionally after each other are useless.
2. Modulo 1 is useless.
3. I think modulo 3 isn't what you intended either...
• 06-13-2010
nvoigt
Code:

```#include <iostream> #include <math.h> #include <time.h> const char* shapes[2] = {"ball", "cube"}; // two arrays for color and shape const char* colors[4] = {"red", "blue", "orange", "green"}; void selectObject(int& color, int& shape) {     color = std::rand() % 4;     shape = std::rand() % 2; } int main() {     std::srand(time(NULL));     int color = 0;     int shape = 0;       for ( int loopNumber = 0; loopNumber <= 100; loopNumber++)   {         selectObject(color, shape);         std::cout<< colors[color]<< " "<< shapes[shape];     }         std::cin.get(); }```
This is the code you probably meant to write. Note that the function is now able to change it's parameters back in the main method because they are passed by reference and doesn't return anything. srand is called just once to seed the random number generator. Note that it's still random. 1,1,1,2,1,3,1,4,1,1,5,3 is a perfectly random sequence. Compare ordinary dice. They don't automatically roll a six once you rolled a 1,2,3,4,5.

You need to use the array size for your modulo operation (read the article posted why this might be bad if you need perfect random numbers... I guess it's fine for now). I replaced 3 and 1 by 4 and 2 but you might want to keep that numbers somewhere else in a central place as constants or #defines.

What did you expect to get anyway? There are 8 possible combinations and you get 100 randoms, there is no way to get 100 unique values out of 8 possible variations. If you need to get 8 combinations in random order, I'd suggest to generate all 8 and shuffle them.
• 06-15-2010
jamort
Thanks nvoigt.. I now understand... And the only reason it was set to 100 was to make sure it wasn't just sptting the same random numbers out then they change