Last active
December 11, 2022 19:41
-
-
Save jfjlaros/a356702037455331f11f626a9f5b6059 to your computer and use it in GitHub Desktop.
Sample from an array without replacement.
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 without replacement. | |
* | |
* \tparam T Array type. | |
* \tparam arraySize Array size. | |
* | |
* \param a Array. | |
* | |
* \return Element of `a`. | |
*/ | |
template <class T, size_t arraySize> | |
T sample(T (& a)[arraySize]) { | |
thread_local size_t size {arraySize}; | |
size_t i {static_cast<size_t>(random(size))}; | |
T tmp {a[i]}; | |
a[i] = a[--size]; | |
a[size] = tmp; | |
if (not size) { | |
size = arraySize; | |
} | |
return tmp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment