Psuedo random number gen

This commit is contained in:
Imbus 2025-02-12 19:47:19 +01:00
parent 40ae617b22
commit 1cd0b619ef
2 changed files with 56 additions and 0 deletions

22
rand.c Normal file
View file

@ -0,0 +1,22 @@
#include <stdint.h>
#include <stdint.h>
#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));
}

34
rand.h Normal file
View file

@ -0,0 +1,34 @@
#pragma once
#include <stdint.h>
/**
* @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);