Skip to content

Instantly share code, notes, and snippets.

@divyang4481
Forked from ekepes/ConsoleApplication2.cs
Created May 28, 2018 06:14
Show Gist options
  • Save divyang4481/6c13e44e81aefc05bfa139cd28a9e9dd to your computer and use it in GitHub Desktop.
Save divyang4481/6c13e44e81aefc05bfa139cd28a9e9dd 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