Reputation: 3
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
Java's setSeed does
(seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)
and next does
(seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
and returning
(int)(seed >>> (48 - bits)).
Upvotes: 0
Views: 1769
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