我需要一个好的伪随机数,它基于一个由字符串和一个 long 组成的密钥。当我使用相同的密钥进行查询时,我应该得到相同的随机数,而且,如果我使用稍微不同的密钥进行查询,我应该得到一个非常不同的数字,即使说密钥中的 long 为 1。我试过这段代码并且随机数是唯一的,但对于相似的数字,它们似乎是相关的。
import java.util.Date;
import java.util.Random;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public class HashKeyTest {
long time;
String str;
public HashKeyTest(String str, long time) {
this.time = time;
this.str = str;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(time).append(str).toHashCode();
}
public static void main(String[] args) throws Exception {
for(int i=0; i<10; i++){
long time = new Date().getTime();
HashKeyTest hk = new HashKeyTest("SPY", time);
long hashCode = (long)hk.hashCode();
Random rGen = new Random(hashCode);
System.out.format("%d:%d:%10.12f\n", time, hashCode, rGen.nextDouble());
Thread.sleep(1);
}
}
}
我拼凑的解决方案。这工作得很好,但我想知道它是否需要这么冗长。
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class HashKeyTest implements Serializable{
long time;
String str;
public HashKeyTest(String str, long time) {
this.time = time;
this.str = str;
}
public double random() throws IOException, NoSuchAlgorithmException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(this);
byte[] bytes = bos.toByteArray();
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
byte[] hash = md5Digest.digest(bytes);
ByteBuffer bb = ByteBuffer.wrap(hash);
long seed = bb.getLong();
return new Random(seed).nextDouble();
}
public static void main(String[] args) throws Exception {
long time = 0;
for (int i = 0; i < 10; i++) {
time += 250L;
HashKeyTest hk = new HashKeyTest("SPY", time);
System.out.format("%d:%10.12f\n", time, hk.random());
Thread.sleep(1);
}
}
}