From 1828f66f16a0d5be513c2ccd08aa8f6b31fd8618 Mon Sep 17 00:00:00 2001 From: James Willis <james.s.willis@durham.ac.uk> Date: Mon, 25 Apr 2016 16:27:22 +0100 Subject: [PATCH] Added function to shuffle an array of particles randomly. Moved random_uniform from testPair/test27cells to tools.c. --- src/tools.c | 30 ++++++++++++++++++++++++++++++ src/tools.h | 3 +++ 2 files changed, 33 insertions(+) diff --git a/src/tools.c b/src/tools.c index d25b7401a1..8fc393144f 100644 --- a/src/tools.c +++ b/src/tools.c @@ -471,3 +471,33 @@ void engine_single_force(double *dim, long long int pid, p.a_hydro[1], p.a_hydro[2]); fflush(stdout); } + +/** + * Returns a random number (uniformly distributed) in [a,b[ + */ +double random_uniform(double a, double b) { + return (rand() / (double)RAND_MAX) * (b - a) + a; +} + +/** + * @brief Randomly shuffle an array of particles. + */ +void shuffle_particles(struct part *parts, const int count) { + + if(count > 1) { + + for(int i=0; i<count - 1; i++) { + + int j = i + random_uniform(0.,(double)(count - 1 - i)); + + struct part particle = parts[j]; + + parts[j] = parts[i]; + + parts[i] = particle; + } + + } + else error("Array not big enough to shuffle!"); + +} diff --git a/src/tools.h b/src/tools.h index ccffc77ceb..8e02126529 100644 --- a/src/tools.h +++ b/src/tools.h @@ -38,4 +38,7 @@ void self_all_density(struct runner *r, struct cell *ci); void pairs_n2(double *dim, struct part *__restrict__ parts, int N, int periodic); +double random_uniform(double a, double b); +void shuffle_particles(struct part *parts, const int count); + #endif /* SWIFT_TOOL_H */ -- GitLab