avatar

Andres Jaimes

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

By Andres Jaimes

- 1 minutes read - 88 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:

1#!/usr/bin/php
2
3<?php
4srand(2);
5
6echo rand(0,10)."\n";
7echo rand(0,5)."\n";
8echo rand(0,4)."\n";
9echo rand(0,6)."\n";

Java version:

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