Get a random number from a list of non contiguos number?

Hello,

assuming i have a series of number as follow {1, 2, 4, 9, 100, 500}

how can i get a random number of the above?

thank you
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
    std::srand(std::time(nullptr));
    
    int numList[] = { 1, 2, 4, 9, 100, 500 };
    int numListCount = 6;

    int randFromList = numList[ std::rand() % numListCount ];
    std::cout << randFromList << std::endl;
}
In C++ you should use <random> for pseudo-random numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <chrono>
#include <iostream>
#include <random>

// Write a function to give you a random number
int random( int min, int max )
{
  // Create and initialize our PRNG
  static auto seed = std::chrono::system_clock::now().time_since_epoch().count();
  thread_local static std::mt19937 prng( seed );
  thread_local static bool init = true;
  if (init) { prng.discard( 10000 ); init = false; }
  
  // Use the PRNG to get a number in the range [min,max]
  return std::uniform_int_distribution <int> ( min, max )( prng );
}

// Use the function
int main()
{
  int numList[] = { 1, 2, 4, 9, 100, 500 };
  int numListCount = 6;
  
  int randFromList = numList[ random( 0, numListCount - 1 ) ];
  std::cout << randFromList << "\n";
}

I know that the function to get a random number is a little overwhelming... but it is the Right Thing to do.

(It keeps a different PRNG per thread. It seeds and "warms-up" the PRNG once, before first use. And it gets an unbiased number in the requested range.)

Keep in mind that if you run this program, you will get an evenly-distributed random number from the list; however, if you run the program again you might not. (Initializing the PRNG is not an evenly-distributed random process. PRNGs work best when they exist for a long time -- restarting the program each time you use it defeats that.)

In any case, even in C (using rand()) you should create a function to get a random number. The % remainder trick skews your results.

Read more here:
http://www.cplusplus.com/faq/beginners/random-numbers/

Hope this helps.
Duoas is right. Just to add some interesting talk about rand: https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
Thank you all for the reply.

Very usefull informations
@Duoas

"int numList[] = { 1, 2, 4, 9, 100, 500 };
int numListCount = 6;"

i use a vector<int> where i push the non contiguos numbers. The returning number are always the same. I'm missing something.
Post your code
It' works, sorry, my mistake. I used only a range of two and for coincidence output was always the second number. I had no patiance to wait thinking that the routine was non functioning

thank you
Last edited on
Topic archived. No new replies allowed.