Skip to content

Secure Random Generator

Secure?? Why??

cpp
// gen [0, upper)*n
// usage:
//  mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
//  auto v1 = genRand(rng, 100000, 10000000);
//  auto v2 = genRand(rng, 100000, 12343212);
vector<int64_t> genRand(mt19937_64& rng, size_t n, int64_t upper) {
    uniform_int_distribution<int64_t> valDistr(0, upper - 1);
    uniform_int_distribution<int64_t> rangDistr(0, n - 1);

    set<int64_t> vals;
    while (vals.size() < n) {
        vals.insert(valDistr(rng));
    }

    vector<int64_t> ret(vals.begin(), vals.end());
    for (size_t i = 0; i < n; ++i) {
        swap(ret[i], ret[rangDistr(rng)]);
    }

    return vector<int64_t>(vals.begin(), vals.end());
}

Changelog

Just observe 👀