Jeff M
Jeff M

Reputation: 3

Javascript implementation of Java's Random class that will generate same sequences with same seed

1st I did multiple searches here and via google trying to find this so sorry ahead of time if I didn't use the right search terms to find it.

I'm rewriting some legacy Java code into Javascript and I've got it all working except for pseudo random number generator... I need the Javascript version of this code to have repeatable output via both the Java and Javascript versions of this code as such I can't use Javascript's RN generator... I also can't change the legacy code to use another RN generator....

So I'm hoping someone had been in the similar situation and has already done this and written/ported Java's RNG into Javascript?

Is it even possible given javascripts bit wise operators only work with a 32 bit word while Java's RNG is based on 64 bit seed... obviously would need two variables each holding 1/2 the seed...


From https://docs.oracle.com/javase/8/docs/api/java/util/Random.html

Upvotes: 0

Views: 1769

Answers (1)

Alnitak
Alnitak

Reputation: 340045

I've created an ES6 class that in my tests produces the same results as the java.util.Random class. So far I've only implemented the .nextInt() public method but it's implemented via the .next() protected method so the other public methods should be easy to implement:

https://gist.github.com/raybellis/4c15a1746724be7bd03964e9d03e0c75

EDIT an enhanced version of this is now available as an NPM:

https://www.npmjs.com/package/java-random

Upvotes: 3

Related Questions