-
Notifications
You must be signed in to change notification settings - Fork 15
/
permute.hh
61 lines (52 loc) · 1.03 KB
/
permute.hh
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Reversible permutations
Copyright 2023 Ahmet Inan <[email protected]>
*/
#pragma once
#include "xorshift.hh"
namespace CODE {
template <int SIZE>
struct FisherYatesShuffle
{
template <typename TYPE>
void operator()(TYPE *array)
{
CODE::Xorshift32 prng;
for (int i = 0; i < SIZE-1; ++i)
std::swap(array[i], array[i + prng() % (SIZE - i)]);
}
};
template <int SIZE>
class ReverseFisherYatesShuffle
{
int seq[SIZE-1];
public:
ReverseFisherYatesShuffle()
{
CODE::Xorshift32 prng;
for (int i = 0; i < SIZE-1; ++i)
seq[i] = i + prng() % (SIZE - i);
}
template <typename TYPE>
void operator()(TYPE *array)
{
for (int i = SIZE-2; i >= 0; --i)
std::swap(array[i], array[seq[i]]);
}
};
template <int SIZE, typename TYPE>
static void BitReversalPermute(TYPE *array)
{
static_assert(SIZE > 0 && (SIZE & (SIZE - 1)) == 0, "SIZE not power of two");
for (int i = 0, j = 0; i < SIZE - 1; ++i) {
if (i < j)
std::swap(array[i], array[j]);
int k = SIZE >> 1;
while (j & k) {
j ^= k;
k >>= 1;
}
j ^= k;
}
}
}