Tag Archive | system clocks

Randomization on a Logical System

Short version of this post: Randomization on a computer system is totally impossible, any “Randomization” you do see is purely clever deception.

Today I’ve been writing the Start Game logic for Sweepy Cleaner. One of the things I have to do during the start of a game is randomize the position of 5 pieces of dirt, and I have spent some of the night tinkering with getting things as random as possible. I say as random as possible because making random numbers is impossible, a number is selected based off of the exact time of the System clock in your PC or on your mobile device. You can prove this with the following C# code:


for(int i = 0; i < 1000; i++)

{

Random r = new Random();

int randomInt = r.Next(0, 3000);

Console.WriteLine("Random Number: " + randomInt);
}

For me this outputted “Random Number:  1742” around 500 times and “Random Number: 2818” around 500 times. This is because this entire loop takes place in just a few milliseconds, not allowing for much change in the System clocks time.  Producing lots of identical numbers in a short space of time can be a pain, especially if you want to initialize a game quickly but want random locations for dirt like I do.  The solution I found is simple, pause the thread for a “Random” amount of time as well before each pass.


Random RandomX = new Random();

System.Threading.Thread.Sleep(new System.TimeSpan(RandomX.Next(0,7)));
x = RandomX.NextDouble() * (RandomX.Next(0, 800));

System.Threading.Thread.Sleep(new System.TimeSpan(RandomX.Next(0,8)));
Random RandomY = new Random();
y = RandomY.NextDouble() * (RandomY.Next(0, 480));

This makes things a little more random but as I said at the beginning Randomization on a computer system is totally impossible. If this makes little sense to you think about what a computer is (an arithmetical and logical processor), there is no such thing as random in Logic, hence there can’t be in a logic system. 🙂

Danny.