简体   繁体   中英

Choose a random number from a list of integer

I have a list of integers intList = {1, 3. 5. 2} (Its just an example integer and size both are unknown). I have to chose a random number from that list.

RandomInt = rand() % intList.size() 

will work in a similar way as RandomInt = rand() % 4

and generate a randon number between 1 to 4. while intList is different.

If I am using RandomInt = std::random_shuffle = (intList, intList.size()) still getting error. I do not know how chose a random number from a list.

Since, as a substep, you need to generate random numbers, you might as well do it the C++11 way (instead of using modulo, which incidentally, is known to have a slight bias toward low numbers ):

Say you start with

#include <iostream>
#include <random>
#include <vector>

int main()
{
    const std::vector<int> intList{1, 3, 5, 2};

Now you define the random generators:

    std::random_device rd; 
    std::mt19937 eng(rd());
    std::uniform_int_distribution<> distr(0, intList.size() - 1);

When you need to generate a random element, you can do this:

    intList[distr(eng)];
}

You just need to use "indirection":

std::vector<int> list{6, 5, 0, 2};
int index = rand() % list.size(); // pick a random index
int value = list[index]; // a random value taken from that list
  int arrayNum[4] = {1, 3, 5, 2};
  int RandIndex = rand() % 5; // random between zero and four
  cout << arrayNum[RandIndex];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM