首页 新闻 会员 周边

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

1
悬赏园豆:5 [已解决问题] 解决于 2016-08-12 09:53
    System.out.println(randomString(-229985452) + " " + randomString(-147909649));    
        
    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();    
    }    

从这篇博客看到的这个问题,但是他的解释,我没看明白。希望大神解释下。

craneyuan的主页 craneyuan | 初学一级 | 园豆:187
提问于:2016-08-11 15:59
< >
分享
最佳答案
0

他找到了一个特殊的随机数种子.这个种子获取到的随机数就是hello world.

伪随机当随机种子指定后生产出来的随机数是固定的.比如第一个一定是h第二个一定是e

收获园豆:5
吴瑞祥 | 高人七级 |园豆:29449 | 2016-08-11 16:21
其他回答(1)
0

 

new Random(-229985452).nextInt(27)
The first 6 numbers that the above random generates are:

8
5
12
12
15
0
and the first 6 numbers that new Random(-147909649).nextInt(27) generates are:

23
15
18
12
4
0
Then just add those numbers to the integer representation of the character ` (which is 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

攻城狮人 | 园豆:202 (菜鸟二级) | 2016-08-17 16:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册