cosmopolitan/libc/mem/shuffle.internal.h
Justine Tunney fa20edc44d
Reduce header complexity
- Remove most __ASSEMBLER__ __LINKER__ ifdefs
- Rename libc/intrin/bits.h to libc/serialize.h
- Block pthread cancelation in fchmodat() polyfill
- Remove `clang-format off` statements in third_party
2023-11-28 14:39:42 -08:00

22 lines
645 B
C

#ifndef COSMOPOLITAN_LIBC_RAND_SHUFFLE_H_
#define COSMOPOLITAN_LIBC_RAND_SHUFFLE_H_
#include "libc/intrin/xchg.internal.h"
/**
* Fisher-Yates shuffle.
*
* @param R is a function like rand() → ≥0
* @param A is a typed array
* @param n is the number of items in A
* @see ARRAYLEN()
*/
#define shuffle(R, A, n) \
do { \
autotype(A) Array = (A); \
for (size_t i = (n)-1; i >= 1; --i) { \
xchg(&Array[i], &Array[R() % (i + 1)]); \
} \
} while (0)
#endif /* COSMOPOLITAN_LIBC_RAND_SHUFFLE_H_ */