From 1cd0b619ef5290807608b5eda11fa535fc7dcaea Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Wed, 12 Feb 2025 19:47:19 +0100 Subject: [PATCH] Psuedo random number gen --- rand.c | 22 ++++++++++++++++++++++ rand.h | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 rand.c create mode 100644 rand.h diff --git a/rand.c b/rand.c new file mode 100644 index 0000000..74cb7ad --- /dev/null +++ b/rand.c @@ -0,0 +1,22 @@ +#include + +#include + +#define BUILD_SEED ((uint64_t)(__TIME__[0]) * (uint64_t)(__TIME__[1]) * \ + (uint64_t)(__TIME__[3]) * (uint64_t)(__TIME__[4]) * \ + (uint64_t)(__TIME__[6]) * (uint64_t)(__TIME__[7])) + +static uint64_t seed = BUILD_SEED; + +void sprand(uint64_t s) { + seed = s ? s : 1; // Ensure the seed is never 0 +} + +uint64_t prand() { + seed = seed * 6364136223846793005ULL + 1; + return seed; +} + +uint64_t prand_range(uint64_t min, uint64_t max) { + return min + (prand() % (max - min + 1)); +} diff --git a/rand.h b/rand.h new file mode 100644 index 0000000..3722734 --- /dev/null +++ b/rand.h @@ -0,0 +1,34 @@ +#pragma once +#include + +/** + * @brief Sets the seed for the custom random number generator. + * + * This function initializes the seed value used by rand_custom(). + * Providing the same seed will produce the same sequence of random numbers. + * + * @param s The seed value (must be nonzero for best results). + */ +void sprand(uint64_t s); + +/** + * @brief Generates a pseudo-random 64-bit number. + * + * Uses a simple Linear Congruential Generator (LCG) to produce + * a sequence of pseudo-random numbers. + * + * @return A pseudo-random 64-bit unsigned integer. + */ +uint64_t prand(); + +/** + * @brief Generates a random number within a specified range. + * + * Produces a random number in the inclusive range [min, max]. + * Ensures uniform distribution by applying a modulo operation. + * + * @param min The lower bound of the range (inclusive). + * @param max The upper bound of the range (inclusive). + * @return A random number between min and max. + */ +uint64_t prand_range(uint64_t min, uint64_t max);