Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code using random strings print "hello world"?

The following print statement would print "hello world". Could anyone explain this?

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

And randomString() looks like this:

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(); } 
like image 701
0x56794E Avatar asked Mar 03 '13 04:03

0x56794E


People also ask

How do you print a random string in C++?

To generate random characters, we should use the rand() method. It generates integer values at random. This number is created using an algorithm associated with the specific time it is called and returns a succession of seemingly unrelated numbers.


2 Answers

The other answers explain why, but here is how.

Given an instance of Random:

Random r = new Random(-229985452) 

The first 6 numbers that r.nextInt(27) generates are:

8 5 12 12 15 0 

and the first 6 numbers that r.nextInt(27) generates given Random r = new Random(-147909649) 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 
like image 112
Eng.Fouad Avatar answered Oct 11 '22 04:10

Eng.Fouad


When an instance of java.util.Random is constructed with a specific seed parameter (in this case -229985452 or -147909649), it follows the random number generation algorithm beginning with that seed value.

Every Random constructed with the same seed will generate the same pattern of numbers every time.

like image 37
FThompson Avatar answered Oct 11 '22 03:10

FThompson