Truly random algorithm in C# – The chaotic user

NET%20LogoIf you’ve already use System.Random in a fine tuned app you’ve probably notice something strange. You get the same random values across sessions. Why ?
If you take a look at the code behind System.Random you’ll notice that it’s mainly based on CPU thick. If the same number of thick elapse each time you do the new/next you potentially get the same random number.
How can we put a kind of truly random, non predictable and chaotic randomness in the algo ? User mouse !
Indeed that’s perhaps the only chaotic stuff in a computer.
Some cryptographic algos use this and it’s not so hard to implement. Indeed it will work only on client app with access to the mouse object and require the user to move the mouse (or the algo will hang).

Here’s the pseudo-code algo I’ll implement :

define RealRandom := Limit += number
	sampleRate = 10 < Random < 20
	numberOfSample = 1 < Random < 10

	for(i < numberOfSample)
		// HERE COMES THE CHAOS !
		samples[i] = MousePositionY * MousePositionX;
		Wait MousePosition != datas[numberOfSample]
		Add 1 to i
		Wait sampleRate
	end

	foreach sample in samples
		returnValue += sample % limit
	end

	return returnValue % limit
end

And here’s the C# implementation.

public static class TrueRandom
{
    public static int NextRandom(int limit)
    {
        int SampleRate = (new Random()).Next(10, 20);
        int NumberOfSample = (new Random()).Next(1, 10);
        long result = 0;

        for(int i = 0; i < NumberOfSample; i++)
        {
            long sample = 0;
            do
            {
                sample = Cursor.Position.X * Cursor.Position.Y;
                Thread.Sleep(10);
            }
            while (sample == Cursor.Position.X * Cursor.Position.Y);
            result += sample % limit;
            Thread.Sleep(SampleRate);
        }

        return (int)result % limit; // Can't cause issue as limit is an integer so the modulo result will always be lower than Int32.MaxValue
    }
}

Catch you next time and keep it bug free !

Published by Emmanuel Istace

Musician, Software developer and guitar instructor. https://emmanuelistace.be/

Leave a comment