Skip to content
Snippets Groups Projects
PseudoRandomGenerator.cs 1.67 KiB
Newer Older
Seilenthal's avatar
Seilenthal committed
using System;

namespace PseudoRandomGenerator
{
    /// <summary>
    /// Linear Congruential Generator (LCG) for pseudo-random number generation without using the built-in Random class
    /// </summary>
    public class LCG
    {
        private long a = 1664525; // Multiplier
        private long c = 1013904223; // Increment
Seilenthal's avatar
Seilenthal committed
        private long m = 4294967296L; // Modulus (2^32 for a large cycle)
Seilenthal's avatar
Seilenthal committed

        private long seed; // Current state (initialized by seed)

        /// <summary>
        /// Initializes the LCG with a specified seed to start sequence
        /// </summary>
        /// <param name="seed">Initial value for generating the sequence (e.g., DataTime.Now.Ticks)</param>
        public LCG(long seed) 
        {
            this.seed = seed;
        }

        /// <summary>
        /// Generates the next pseudo-random number in the sequence
        /// </summary>
        /// <returns>A pseudo-random number based on the internal LCG algorithm</returns>
        public long Next()
        {
            // Update the seed using the LCG-formula
            seed = (a * seed + c) % m;
            return seed;
        }

        /// <summary>
        /// Generates a pseudo-random integer within a specified range (min, max)
        /// </summary>
        /// <param name="min">The inclusive lower bound of the random number</param>
        /// <param name="max">The exclusive upper bound of the random number</param>
        /// <returns>A pseudo-random integer between min and max</returns>
        public long Next(int min, int max)
        {
            // Map the result of Next() to the specified range
            return (int)(Next() % (max - min)) + min;
        }

    }
}