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

以下打印声明将打印“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();
}

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

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


其他答案解释了为什么,但这里是如何。

给定一个Random的实例:

Random r = new Random(-229985452)

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

8
5
12
12
15
0

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

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

我会把它留在这里。 如果你已经掌握了一些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
链接地址: http://www.djcxy.com/p/3479.html

上一篇: Why does this code using random strings print "hello world"?

下一篇: java static initialization with inheritance