avatar

Andres Jaimes

Why you should not initialize a random generator with a static number

By Andres Jaimes

- 1 minutes read - 78 words

The following examples use random generated numbers initialized with a static seed. Never do it like this.

Run the following examples multiple times to understand why it is important to have a good seed.

PHP version:

#!/usr/bin/php

<?php
srand(2);

echo rand(0,10)."\n";
echo rand(0,5)."\n";
echo rand(0,4)."\n";
echo rand(0,6)."\n";

Java version:

import java.util.*;

/**
 * @see https://docs.oracle.com/javase/7/docs/api/java/util/Random.html
 */
public class RandomDemo {
    public static void main( String args[] ){
        Random r = new Random(2);
        System.out.println(r.nextInt(10));
        System.out.println(r.nextInt(5));
        System.out.println(r.nextInt(4));
        System.out.println(r.nextInt(6));
    }
}