Unique random integers

Pages: 12
I would be surprised if any implementations existed that didn’t use the Knuth Fisher Yates algorithm.

If I read cppreference's page on std::shuffle correctly for possible implementation it does appear the algorithm is used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template<class RandomIt, class URBG>
void shuffle(RandomIt first, RandomIt last, URBG&& g)
{
    typedef typename std::iterator_traits<RandomIt>::difference_type diff_t;
    typedef std::uniform_int_distribution<diff_t> distr_t;
    typedef typename distr_t::param_type param_t;
 
    distr_t D;
    diff_t n = last - first;
    for (diff_t i = n-1; i > 0; --i) {
        using std::swap;
        swap(first[i], first[D(g, param_t(0, i))]);
    }
}


That snippet is almost indecipherable to me, but it is intriguing to try to pick it apart and understand what is happening.
Topic archived. No new replies allowed.
Pages: 12