2016-05-11 41 views
0

超級noob問題(從一個人不理解的東西,按位):隨機數發生器用java長期種子值

我在JavaScript中使用下面的僞隨機數發生器(我的服務器上)。

Math.seed = function(s) { 
    var m_w = s; 
    var m_z = 987654321; 
    var mask = 0xffffffff; 

    return function() { 
     m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask; 
     m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask; 

     var result = ((m_z << 16) + m_w) & mask; 
     result /= 4294967296; 

     return result + 0.5; 
    } 
} 

var myRandomFunction = Math.seed(1234); 
var randomNumber = myRandomFunction(); 

現在我想用它在Java(在我的客戶端)。這適用於int種子值(例如1234的種子在JS和Java上給出相同的數字),但是我的種子值很長。我該如何改變按位運算符?

public class CodeGenerator { 
    private int m_w; 
    private int mask; 
    private int m_z; 

    public CodeGenerator(int seed) { 
     m_w = seed; 
     m_z = 987654321; 
     mask = 0xffffffff; 
    } 

    public int nextCode() { 
     m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask; 
     m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask; 
     int result = ((m_z << 16) + m_w) & mask; 
     double result2 = result/4294967296.0; 
     return (int)Math.floor((result2 + 0.5) * 999999); 
    } 
} 
+0

出於好奇......爲什麼不使用https://docs.oracle.com/javase/7/docs/api/java/util/Random.html? – Niels

+0

用long聲明變量和方法。 – fhofmann

+0

@fhofmann這會產生不同的數字。我需要他們相同的種子。 – obiwahn

回答

0

在Java中,您需要將種子屏蔽爲unsigned int,然後它會生成與JS版本相同的數字。

新的構造:

public CodeGenerator(long seed) { 
    mask = 0xffffffff; 
    m_w = (int) (seed & mask); 
    m_z = 987654321; 
} 
0

你試過只聲明種子和第一個結果爲多久?

public class CodeGenerator { 
    private long m_w; 
    private int mask; 
    private int m_z; 

    public static void main(String... a){ 
     System.out.println(new CodeGenerator(1234).nextCode()); //result = 237455 
     System.out.println(new CodeGenerator(1234567891234L).nextCode()); //result = 246468 
    } 

    public CodeGenerator(long seed) { 
     m_w = seed; 
     m_z = 987654321; 
     mask = 0xffffffff; 
    } 

    public int nextCode() { 
     m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask; 
     m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask; 
     long result = ((m_z << 16) + m_w) & mask; 
     double result2 = result/4294967296.0; 
     return (int)Math.floor((result2 + 0.5) * 999999); 
    } 
}