From 2d276366440af245004806e217301bf2446c1a90 Mon Sep 17 00:00:00 2001 From: chme Date: Sat, 15 Oct 2016 10:06:18 +0200 Subject: [PATCH] [rng] Add function to shuffle an int array --- src/rng.c | 19 +++++++++++++++++++ src/rng.h | 3 +++ 2 files changed, 22 insertions(+) diff --git a/src/rng.c b/src/rng.c index 5b57e06a..d36b13b3 100644 --- a/src/rng.c +++ b/src/rng.c @@ -144,3 +144,22 @@ shuffle_ptr(struct rng_ctx *ctx, void **values, int len) } } +/* Fisher-Yates shuffling algorithm + * Durstenfeld in-place shuffling variant + */ +void +shuffle_int(struct rng_ctx *ctx, int *values, int len) +{ + int i; + int32_t j; + int tmp; + + for (i = len - 1; i > 0; i--) + { + j = rng_rand_range(ctx, 0, i + 1); + + tmp = values[i]; + values[i] = values[j]; + values[j] = tmp; + } +} diff --git a/src/rng.h b/src/rng.h index b6a2c34f..12d980c8 100644 --- a/src/rng.h +++ b/src/rng.h @@ -21,5 +21,8 @@ rng_rand_range(struct rng_ctx *ctx, int32_t min, int32_t max); void shuffle_ptr(struct rng_ctx *ctx, void **values, int len); +void +shuffle_int(struct rng_ctx *ctx, int *values, int len); + #endif /* !__RNG_H__ */