Ever wanted to program something that looks like a random outcome, but comes out the same way every time based on some kind of input? Here is one way. The modulus (%) operator is the key because it produces an output that seems to vary randomly. I had to implement something like this in Javascript.

  1. function pseudoRandom( seed, maximum ){
  2.         n = (314159265 * seed + 2718281) % 65536;
  3.         c = Math.round( ((n / 65536) * 100) % 100 );
  4.         output = Math.floor( c/100 * maximum );
  5.        
  6.         return output;
  7. }

Simply provide a seed argument that is an integer that varies based on user input, or some state of your application. This function will output a number between 0 and the ‘maximum’ argument.

I used this to create a simple Javascript game. It could be applied to any situation where you want to present the user with outcomes that feel random but are consistent based on what they do. Of course there are limits to how random these outcomes actually are. But in general it works well enough to give the experience of randomness.

Leave a Reply