协慌网

登录 贡献 社区

为什么这段代码使用随机字符串打印 “hello world”?

以下 print 语句将打印 “hello world”。谁能解释一下呢?

System.out.println(randomString(-229985452) + " " + randomString(-147909649));

randomString()看起来像这样:

public static String randomString(int i)
{
    Random ran = new Random(i);
    StringBuilder sb = new StringBuilder();
    while (true)
    {
        int k = ran.nextInt(27);
        if (k == 0)
            break;

        sb.append((char)('`' + k));
    }

    return sb.toString();
}

答案

其他答案解释了原因,但这里是如何。

给定一个Random实例:

Random r = new Random(-229985452)

r.nextInt(27)生成的前 6 个数字是:

8
5
12
12
15
0

r.nextInt(27)生成给定的Random r = new Random(-147909649)的前 6 个数字是:

23
15
18
12
4
0

然后只需将这些数字添加到字符`的整数表示形式(即 96):

8  + 96 = 104 --> h
5  + 96 = 101 --> e
12 + 96 = 108 --> l
12 + 96 = 108 --> l
15 + 96 = 111 --> o

23 + 96 = 119 --> w
15 + 96 = 111 --> o
18 + 96 = 114 --> r
12 + 96 = 108 --> l
4  + 96 = 100 --> d

当使用特定种子参数(在本例中为-229985452-147909649 )构造java.util.Random的实例时,它遵循以该种子值开头的随机数生成算法。

每个使用相同种子构造的Random将每次生成相同的数字模式。

我会把它留在这里。谁有很多(CPU)的时间,随时可以试验:) 另外,如果你已经掌握了一些 fork-join-fu 来使这个东西烧掉所有 CPU 内核(只是线程很无聊,对吗?),请分享你的代码。我将不胜感激。

public static void main(String[] args) {
    long time = System.currentTimeMillis();
    generate("stack");
    generate("over");
    generate("flow");
    generate("rulez");

    System.out.println("Took " + (System.currentTimeMillis() - time) + " ms");
}

private static void generate(String goal) {
    long[] seed = generateSeed(goal, Long.MIN_VALUE, Long.MAX_VALUE);
    System.out.println(seed[0]);
    System.out.println(randomString(seed[0], (char) seed[1]));
}

public static long[] generateSeed(String goal, long start, long finish) {
    char[] input = goal.toCharArray();
    char[] pool = new char[input.length];
    label:
    for (long seed = start; seed < finish; seed++) {
        Random random = new Random(seed);

        for (int i = 0; i < input.length; i++)
            pool[i] = (char) random.nextInt(27);

        if (random.nextInt(27) == 0) {
            int base = input[0] - pool[0];
            for (int i = 1; i < input.length; i++) {
                if (input[i] - pool[i] != base)
                    continue label;
            }
            return new long[]{seed, base};
        }

    }

    throw new NoSuchElementException("Sorry :/");
}

public static String randomString(long i, char base) {
    System.out.println("Using base: '" + base + "'");
    Random ran = new Random(i);
    StringBuilder sb = new StringBuilder();
    for (int n = 0; ; n++) {
        int k = ran.nextInt(27);
        if (k == 0)
            break;

        sb.append((char) (base + k));
    }

    return sb.toString();
}

输出:

-9223372036808280701
Using base: 'Z'
stack
-9223372036853943469
Using base: 'b'
over
-9223372036852834412
Using base: 'e'
flow
-9223372036838149518
Using base: 'd'
rulez
Took 7087 ms