RobsonLittle Red Book ▸ Random sequence

Chapter 7 - Question 10

Design a program to produce a randomly selected permutation of the integers 1 to 5 such that each appears once and once only.

Solution 1

<?    // first, declare the numbers in an array    $numbers = array(1, 2, 3, 4, 5);    // randomly change the order    shuffle($numbers);    // output the sequence    echo implode(', ', $numbers); ?>

Which produces:

1, 3, 5, 2, 4

Solution 2

This type of script could be used to generate random lottery numbers.

<?    // how many numbers are needed    define(HIGHEST, 49);    // the amount of numbers to generate    define(GENERATE, 6);    // start the array    $numbers = array();    // add each number to the array    for ($n = 1; $n <= HIGHEST; $n++)        // add that number        $numbers[] = $n;            // randomly change the order    shuffle($numbers);    // output the first 6 numbers    echo implode(', ', array_slice($numbers, 0, GENERATE)); ?>

Which produces:

36, 27, 30, 2, 47, 29

Log

© 2004-20 robson | cc unless stated