Last active
December 29, 2022 16:39
-
-
Save jfjlaros/b0ce917a56c64325b26be8729553c69b to your computer and use it in GitHub Desktop.
Sample from an array, but disallow the last `historySize` results.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Sample from an array, but disallow the last `historySize` results. | |
* | |
* \tparam historySize History size. | |
* \tparam T Array type. | |
* \tparam arraySize Array size. | |
* | |
* \param a Array. | |
* | |
* \return Element of `a`. | |
*/ | |
template <size_t historySize, class T, size_t arraySize> | |
T sample(T (& a)[arraySize]) { | |
thread_local size_t offset {0}; | |
size_t i {(offset + random(historySize, arraySize)) % arraySize}; | |
size_t j {(offset + historySize) % arraySize}; | |
T tmp {a[i]}; | |
a[i] = a[j]; | |
a[j] = tmp; | |
offset = (offset + 1) % arraySize; | |
return tmp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment