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)
		samples[i] = MousePositionY * MousePositionX;
		Wait MousePosition != datas[numberOfSample]
		Add 1 to i
		Wait sampleRate

	foreach sample in samples
		returnValue += sample % limit

	return returnValue % limit

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;
                sample = Cursor.Position.X * Cursor.Position.Y;
            while (sample == Cursor.Position.X * Cursor.Position.Y);
            result += sample % limit;

        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 !

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s