Skip to content

Instantly share code, notes, and snippets.

@ekepes
Last active January 8, 2022 05:00
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ekepes/8aed1310c3e7af31c99d to your computer and use it in GitHub Desktop.
Save ekepes/8aed1310c3e7af31c99d to your computer and use it in GitHub Desktop.
C# implementation of a Linear Congruential Generator (LCG) for psuedorandom number generation
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var freq = new int[20];
var rng = new RandomNumberGenerator();
for (int i = 0; i < 100; i++)
{
var rnd = rng.Next(20);
freq[rnd] += 1;
Console.Write("{0}, ", rnd);
}
Console.WriteLine("Done.");
for (int i = 0; i < 20; i++)
{
Console.Write("{0}={1}\t", i, freq[i]);
}
Console.ReadLine();
}
}
// Based on https://en.wikipedia.org/wiki/Linear_congruential_generator
class RandomNumberGenerator
{
private const long m = 4294967296; // aka 2^32
private const long a = 1664525;
private const long c = 1013904223;
private long _last;
public RandomNumberGenerator()
{
_last = DateTime.Now.Ticks % m;
}
public RandomNumberGenerator(long seed)
{
_last = seed;
}
public long Next()
{
_last = ((a * _last) + c) % m;
return _last;
}
public long Next(long maxValue)
{
return Next() % maxValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment