aboutsummaryrefslogtreecommitdiffstats
path: root/util/random/shuffle.h
blob: 579f3073ee7f818cbefc2f28677c71a9bebfacb0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#pragma once

#include "fast.h" 
#include "entropy.h" 
 
#include <util/generic/utility.h>
 
// some kind of https://en.wikipedia.org/wiki/Fisher–Yates_shuffle#The_modern_algorithm 
 
template <typename TRandIter, typename TRandIterEnd> 
inline void Shuffle(TRandIter begin, TRandIterEnd end) {
    static_assert(sizeof(end - begin) <= sizeof(size_t), "fixme"); 
    static_assert(sizeof(TReallyFastRng32::RandMax()) <= sizeof(size_t), "fixme"); 
 
    if ((size_t)(end - begin) < (size_t)TReallyFastRng32::RandMax()) { 
        Shuffle(begin, end, TReallyFastRng32(Seed())); 
    } else { 
        Shuffle(begin, end, TFastRng64(Seed())); 
    }
}

template <typename TRandIter, typename TRandIterEnd, typename TRandGen>
inline void Shuffle(TRandIter begin, TRandIterEnd end, TRandGen&& gen) { 
    const size_t sz = end - begin;

    for (size_t i = 1; i < sz; ++i) {
        DoSwap(*(begin + i), *(begin + gen.Uniform(i + 1))); 
    }
}

template <typename TRange>
inline void ShuffleRange(TRange& range) {
    auto b = range.begin(); 
 
    Shuffle(b, range.end()); 
}

template <typename TRange, typename TRandGen>
inline void ShuffleRange(TRange& range, TRandGen&& gen) {
    auto b = range.begin(); 
 
    Shuffle(b, range.end(), gen); 
}