我需要基于由一个字符串和一个长的关键良好的伪随机数。 我应该得到相同的随机数,当我查询使用相同的密钥和也,我如果我查询使用稍微不同的密钥得到一个非常不同的数字,即使说长久的关键是关闭的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);
}
}
}