dimanche 2 octobre 2016

Random class seeds and nextInt effect on them based on seed value

So I have chopped up the code in an effort to clean this up a bit. My confusion is on B1 vs. B2. Is B2 just reaching the upper limit of what a Long value can be and that is why nextInt always returns a "1"? The assignment is to explain the behavior exhibited by each header (B1, B2...)

private static final long CONST1 = 340277109L;
private static final long CONST2 = 101010101L;
private static final long CONST3 = -5722202916L;
private static final long CONST4 = -1010101010L;
private static final long CONSTA = CONST1 + CONST2;
private static final long CONSTB = CONST3 + CONST4;
...
Random random = new Random(CONSTA);
System.out.print("B1: ");
for (int i = 0; i < 10; i++)
    System.out.print(random.nextInt(10) + " "); /* B1 */

System.out.print("\nB2: ");
random = new Random(CONSTB);
for (int i = 0; i < 10; i++)
    System.out.print(random.nextInt(10) + " "); /* B2 */

Output:

B1: 1 1 1 1 1 1 1 1 1 1 
B2: 0 1 2 3 4 5 6 7 8 9




Aucun commentaire:

Enregistrer un commentaire