Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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