Skip to content

Instantly share code, notes, and snippets.

@ekepes
Last active January 8, 2022 05:00
Show Gist options
  • Save ekepes/8aed1310c3e7af31c99d to your computer and use it in GitHub Desktop.
Save ekepes/8aed1310c3e7af31c99d to your computer and use it in GitHub Desktop.

Revisions

  1. ekepes created this gist Dec 21, 2015.
    57 changes: 57 additions & 0 deletions ConsoleApplication2.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    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;
    }
    }
    }