Skip to content

Instantly share code, notes, and snippets.

@jfjlaros
Last active December 29, 2022 16:39
Show Gist options
  • Save jfjlaros/b0ce917a56c64325b26be8729553c69b to your computer and use it in GitHub Desktop.
Save jfjlaros/b0ce917a56c64325b26be8729553c69b to your computer and use it in GitHub Desktop.
Sample from an array, but disallow the last `historySize` results.
/* 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