简体   繁体   English

不重复的随机数生成器 (cpp/c++)

[英]random number generator that doesn't repeat it self (cpp/c++)

I want to make a function that generates numbers but doesn't repeat it self.我想制作一个 function 来生成数字但不会自行重复。 If every number is generated the array can be emptied and it can start over again.如果生成了每个数字,则可以清空数组并重新开始。

This is the code I made but it doesn't work.这是我编写的代码,但它不起作用。 The comments in the code explains the code a little.代码中的注释对代码做了一些解释。 The largest number that is allowed is "howManyWords".允许的最大数字是“howManyWords”。 This is used to display words which are stored in an array这用于显示存储在数组中的单词

I want to use it like this: array\[random()\]我想这样使用它: array\[random()\]

#include <stdio.h>
#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;
//public scope
int howManyWords; // how many words you have enter

int random(){
    int random;
    int numbers[howManyWords];
    srand(time(0)); //changing the algorithm
    random = rand() % howManyWords;
    numbers[random] = random; // store the digit in the position in the array equal to the digit that is generated
    for(int i=0; i<howManyWords; i++){ // going through every element in the array
        if(numbers[i] == random){ // if the number is already generated, generate a different number
        random = rand() % howManyWords;
        }
    }
    return random;
}

Rather than your function, which discards the state of which numbers it has returned each time it is called, you should use a function object.而不是您的 function,它会丢弃每次调用时返回的数字 state,您应该使用 function object。

struct random_t {
    random_t(int max) : values(max), current(max) {
        std::iota(values.begin(), values.end(), 0); 
    }

    template<typename URBG = std::random_device &>
    int operator()(URBG&& urbg = default_random) {
        if (current == values.size()) { 
            shuffle(std::forward<URBG>(urbg));
        } 
        return values[current++]; 
    }
private:
    template<typename URBG>
    void shuffle(URBG&& urbg) { 
        std::shuffle(values.begin(), values.end(), std::forward<URBG>(urbg));
        current = 0; 
    }

    std::vector<int> values;
    std::vector<int>::size_type current;
    static thread_local std::random_device default_random;
};

See it live现场观看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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