mirror of
https://github.com/aicodix/code.git
synced 2026-04-27 22:35:44 +00:00
added reversible Fisher-Yates shuffle
This commit is contained in:
parent
476a346295
commit
e0857552bb
1 changed files with 39 additions and 0 deletions
39
permute.hh
Normal file
39
permute.hh
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
/*
|
||||||
|
Reversible permutations
|
||||||
|
|
||||||
|
Copyright 2023 Ahmet Inan <inan@aicodix.de>
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "xorshift.hh"
|
||||||
|
|
||||||
|
namespace CODE {
|
||||||
|
|
||||||
|
template <int SIZE>
|
||||||
|
class ReversibleFisherYatesShuffle
|
||||||
|
{
|
||||||
|
int seq[SIZE-1];
|
||||||
|
public:
|
||||||
|
ReversibleFisherYatesShuffle()
|
||||||
|
{
|
||||||
|
CODE::Xorshift32 prng;
|
||||||
|
for (int i = 0; i < SIZE-1; ++i)
|
||||||
|
seq[i] = i + prng() % (SIZE - i);
|
||||||
|
}
|
||||||
|
template <typename TYPE>
|
||||||
|
void forward(TYPE *array)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < SIZE-1; ++i)
|
||||||
|
std::swap(array[i], array[seq[i]]);
|
||||||
|
}
|
||||||
|
template <typename TYPE>
|
||||||
|
void reverse(TYPE *array)
|
||||||
|
{
|
||||||
|
for (int i = SIZE-2; i >= 0; --i)
|
||||||
|
std::swap(array[i], array[seq[i]]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue