Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-repeating random number generator

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?

like image 460
Jpeh Noynay Avatar asked Mar 21 '11 18:03

Jpeh Noynay


1 Answers

What I would do:

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

EDIT: I have no idea how the questions are being stored, so.. :)

I am assuming the questions are being stored in a vector or somesuch with random access. Now I have generated 10 random numbers which don't repeat: 7, 4, 12, 17, 1, 13, 9, 2, 3, 10.

I would use those as indices for the vector of questions:

std::vector<std::string> questions;
//fill with questions
for(int i = 0; i < number_of_questions; i++)
{
    send_question_and_get_answer(questions[i]);
}
like image 78
The Communist Duck Avatar answered Oct 03 '22 08:10

The Communist Duck