Non-repeating random number generator

后端 未结 7 1829
清酒与你
清酒与你 2020-12-21 00:57

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 ran         


        
7条回答
  •  爱一瞬间的悲伤
    2020-12-21 01:29

    Why not use some STL to perform the checks for you? The idea:

    Create an (initially empty) set of 10 integers that will be the indices of the random questions (they will be distinct as a set forbids duplicate items). Keep pushing random numbers in [0, num_of_questions-1] in there until it grows to a size of 10 (duplicates will get rejected automatically). When you have that set ready, iterate over it and output the questions of the corresponding indexes:

    std::vector questions = /* I am assuming questions are stored in here */
    std::set random_indexes;
    
    /* loop here until you get 10 distinct integers */
    while (random_indexes.size() < 10) random_indexes.insert(rand() % questions.size());
    
    for (auto index: random_indexes){
        std::cout << questions[index] <

    I may be missing something, but it seems to me the answers that use shuffling of either questions or indexes perform more computations or use an unnecessary memory overhead.

提交回复
热议问题