Implement MappedShuffle for tracking the permutation of an array
This commit is contained in:
24
src/random.h
24
src/random.h
@@ -8,6 +8,7 @@
|
||||
|
||||
#include "uint256.h"
|
||||
|
||||
#include <functional>
|
||||
#include <stdint.h>
|
||||
|
||||
/**
|
||||
@@ -24,6 +25,29 @@ uint64_t GetRand(uint64_t nMax);
|
||||
int GetRandInt(int nMax);
|
||||
uint256 GetRandHash();
|
||||
|
||||
/**
|
||||
* Rearranges the elements in the range [first,first+len) randomly, assuming
|
||||
* that gen is a uniform random number generator. Follows the same algorithm as
|
||||
* std::shuffle in C++11 (a Durstenfeld shuffle).
|
||||
*
|
||||
* The elements in the range [mapFirst,mapFirst+len) are rearranged according to
|
||||
* the same permutation, enabling the permutation to be tracked by the caller.
|
||||
*
|
||||
* gen takes an integer n and produces a uniform random output in [0,n).
|
||||
*/
|
||||
template <typename RandomAccessIterator, typename MapRandomAccessIterator>
|
||||
void MappedShuffle(RandomAccessIterator first,
|
||||
MapRandomAccessIterator mapFirst,
|
||||
size_t len,
|
||||
std::function<int(int)> gen)
|
||||
{
|
||||
for (size_t i = len-1; i > 0; --i) {
|
||||
auto r = gen(i+1);
|
||||
std::swap(first[i], first[r]);
|
||||
std::swap(mapFirst[i], mapFirst[r]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed insecure_rand using the random pool.
|
||||
* @param Deterministic Use a deterministic seed
|
||||
|
||||
Reference in New Issue
Block a user