Cross-Language Random Number GeneratorTags: javascript, csharp, c, web — 13th of October 2011

The what?

This is a cross-language random number generator using the Mersenne Twister Algorithm. You can read all about the algorithm itself from Wikipedia. You'll notice that the algorithm itself is pretty simple to implement and there is many implementations for many programming languages. So I took some of them and made them generate the same random numbers given a seed.

The why?

I wrote this for a simple problem that we had at Eduware. We needed to scramble a student's exam and wanted to be able to do the actual scrambling on the students computer (Javascript) and also on our server (C#). But we needed the scrambled exam from both Javascript & C# to look exactly the same. And there was only one problem, the random number generator. We needed to be able to generate the same random numbers in C# and in Javascript. And to make things more painful, some browsers (Safari) seemed to handle floating numbers differently. We needed a random number generator that will never look different.

The how?

Javascript:
var twister = new MersenneTwister(42);
for (var i = 0; (i < 20); i++) {
     document.write(i + ") " + twister.Next(100) + "
"); }
C#:
        MersenneTwister twister = new MersenneTwister(42);
        for (int i = 0; (i < 20); i++)
            Console.WriteLine(i.ToString() + ") " + twister.Next(100));
C:
    int i;
    init_genrand(42);
    for (i=0; i<20; i++) {
      printf("%d) %d \n", i, rndNext(100));
    }
They all have the same output:
0) 96
1) 27
2) 85
3) 73
4) 19
5) 20
6) 33
7) 37
8) 19
9) 9
10) 42
11) 74
12) 90
13) 18
14) 35
15) 46
16) 52
17) 64
18) 33
19) 73

Code

Here is the code. Download Here

Do note that I didn't write the whole thing, but only took existing code and made them all output the same values. Reference: http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html