通过随机数打印hello-world
例如如下代码:
import java.util.Random;
public class Main {
public static void main(String[] args) {
System.out.println(randomString(-229985452)+" "+randomString(-147909649));
}
private static String randomString(int i) {
Random random = new Random(i);
StringBuilder sb = new StringBuilder();
while (true) {
// 这个27就是0(截止)和26个字母
int k = random.nextInt(27);
if (k==0) {
break;
}
// '`' 是a之前的ascii字符
sb.append((char)('`'+k));
}
return sb.toString();
}
}
结果:
其实大概也知道为啥,Random
设置随机种子,那其实接下来的随机数就固定了,再随机也是函数模拟的罢了,有规律可循,但是这通过随机种子找到特定的字符串也太秀或者太闲了吧。
再一看,误解了,seed
可以代码来找啊:
private static long getSeed(String word) throws NoSuchFieldException {
int idx = 0;
int n = word.length();
// 先找个几十亿吧,怕把电脑跑死
for (long i = Integer.MIN_VALUE;i<=Integer.MAX_VALUE;i++) {
Random rand = new Random(i);
boolean ok =true;
for(int j=0;j<n;j++) {
if (rand.nextInt(27)==(int)(word.charAt(j)-'`')) {
} else {
ok = false;
break;
}
}
if (ok&&rand.nextInt(27)==0) {
return i;
}
}
throw new NoSuchFieldException("can't find such string:");
}
看下测试结果:
public static void main(String[] args) throws NoSuchFieldException {
// System.out.println(getSeed("hello"));
// System.out.println(getSeed("word"));
System.out.println(randomString(-889384708)+" "+randomString(-2121591634)); // hello word
System.out.println(randomString(-229985452)+" "+randomString(-147909649)); // hello world
}
果然不唯一,-889384708
和-229985452
都能对应hello
。
很明显,越长越不好找。