Non-repeating random number generator

2020-04-07 06:01发布

I'd like to make a number generator that does not repeat the number it has given out already (C++).

All I know is:

int randomgenerator(){
  int random;
  srand(time(0));
  random = rand()%11;
  return(random);
} // Added this on edition

That function gives me redundant numbers.

I'm trying to create a questionnaire program that gives out 10 questions in a random order and I don't want any of the questions to reappear.

Does anyone know the syntax?

7条回答
迷人小祖宗
2楼-- · 2020-04-07 06:33

Should look more like this: (Note: does not solve your original problem).

int randomgenerator(){
  int random;

  // I know this looks re-dunand compared to %11
  // But the bottom bits of rand() are less random than the top
  // bits do you get a better distribution like this.

  random = rand() / (RAND_MAX / 11);

  return random;
}

int main()
{
    // srand() goes here.
    srand(time(0));

    while(true)
    {
        std::cout << randomgenerator() << "\n";
    }
}

A better way to solve the original problem is to pre-generate the numbers so you know that each number will appear only once. Then shuffle the order randomly.

int main()
{
    int data[] =  { 0,1,2,3,4,5,6,7,8,9,10,11};
    int size   =  sizeof(data)/sizeof(data[0]);

    std::random_shuffle(data, data + size);

    for(int loop = 0; loop < size; ++loop)
    {
        std::cout << data[loop] << "\n";
    }
}
查看更多
登录 后发表回答