Random unique numbers

Hello everyone,

How can I generate a unique random number?

With the function rand() % tam the generated numbers are repeated together.

Thank`s for the help.

Yuri.
1
2
3
4
#include <time.h>

//use this at the start of main
srand(time(NULL));


Your random numbers will be, random.
Last edited on
Generate a random number as usual, if it's already been used try again, otherwise return the random number. You should also remember to call srand(time(NULL)), otherwise the same random sequence will be generated between runs
e.g
1
2
3
4
5
6
7
8
9
10
11
12
int generateUniqueInt()
{
  static vector<int> generatedValues;

  int num = rand() % tam;

  while(contains(generatedValues, num)) //You'll need a function to check whether the num is in this vector
  {
    num = rand() % tam;
  }
  return num;
}
Might be going offtopic but its the first time i ive seen something that could use a single line do while loop

so..
1
2
3
4
5
6
int generateUniqueInt()
{
  static vector<int> generatedValues;
  do int num = rand() % tam; while(contains(generatedValues, num));
  return num;
}
is this possible, or not allowed, like does it need braces or can do while work like this?
Oh my o_O, I believe that would work (we'd need int num outside the loop, though). Single do while loops aren't something you see everyday
Last edited on
If you're gonna go with ugly coding style, this might be a little more readable:

 
while( contains( generatedValues, num = rand() % tam ) ) ;

You'll also have to make sure to add the number to your list of generatedValues each time you find a new value.

This also has issues if you have a long-running program or if you generate a large number of random numbers -- space issues with a std::vector being one of them.
Topic archived. No new replies allowed.