문자열과 긴 숫자로 구성된 키를 기반으로 올바른 의사 난수가 필요합니다. 동일한 키를 사용하여 쿼리 할 때 동일한 임의의 숫자를 가져와야하며, 키가 길면 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);
}
}
}
해결책 I 함께. 이것은 꽤 잘 작동하지만, 이것이 장황 할 필요가 있는지 궁금합니다.
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);
}
}
}
게임을 포함하여 대부분의 경우 솔루션이 적합하지 않습니다. 기본적으로 각 호출에 대해 RNG를 다시 인스턴스화합니다. – ingyhere