Non Repeating Random Number Generator

I would like to create a number generator that does not repeat the number that it already issued (C ++).

All I know is:

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

This function gives me redundant numbers.

I am trying to create a questionnaire program that gives 10 questions in random order, and I do not want any questions to appear again.

Does anyone know the syntax?

+5
source share
5 answers

What will i do:

  • Create a vector of length N and fill it with values ​​1,2, ... N.
  • Use std :: random_shuffle .
  • If you said 30 elements and only want 10, use the first 10 of the vector.

EDIT: I have no idea how questions are stored, therefore .. :)

, somesuch . 10 , : 7, 4, 12, 17, 1, 13, 9, 2, 3, 10.

:

std::vector<std::string> questions;
//fill with questions
for(int i = 0; i < number_of_questions; i++)
{
    send_question_and_get_answer(questions[i]);
}
+18

" ".

(, vector<int> , , ):

  • R 0 N-1, N -
  • R "" .
  • "selected questions" ,
  • R ( N 1)
  • 1
+7

, , , ( "" ).

++ :

#include <vector>
#include <algorithms>

std::vector<int> question_numbers;
for (unsigned int i = 0; i < 10; ++i)
    question_numbers.push_back(i+1);
std::random_shuffle(question_numbers.begin(), question_numbers.end());

// now dole out the questions based on the shuffled numbers

, , , . , , .

+6

10 ( 1-10), , std::random_shuffle. .

+4

: (: ).

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";
    }
}

The best way to solve the original problem is to pre-generate numbers so that you know that each number will be displayed only once. Then randomly mix the order.

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";
    }
}
+1
source

All Articles