# Robson ▸ Little Red Book ▸ Random Numbers #4

## Chapter 7 - Question 5

The traffic arriving at a junction is observed for an hour. Each minute the number of arrivals at the junction is recorder and the data tabulated:

 Number of arrivals in each one minute period 0 1 2 3 4 5 6 7 8 9 10 Number of one minute periods having that number of arrivals 4 15 12 9 6 5 3 1 2 1 1

Design a function to return a random number based on this distribution.

Generalise the function to use a similar distribution as a parameter.

### Solution 1

PHP:

`<?` `    \$traffic = array(` `                     0 =>  4,` `                     1 => 15,` `                     2 => 12,` `                     3 =>  9,` `                     4 =>  6,` `                     5 =>  5,` `                     6 =>  3,` `                     7 =>  1,` `                     8 =>  2,` `                     9 =>  1,` `                    10 =>  1` `                    );` `    \$pos = mt_rand(1, 60);` `    foreach(\$traffic as \$key => \$minute)` `    {` `        \$total += \$minute;` `        if (\$total >= \$pos)` `        {` `            echo \$key;` `            break;` `        }` `    }` `?>`

Which produces:

1

That seemed a bit easy, so I thought I'd have a go at trying to make the smallest possible solution:

`<?\$t=array(4,15,12,9,6,5,3,1,2,1,1);\$p=rand(1,60);for(\$n=0;\$a<\$p;)\$a+=\$t[\$n++];echo --\$n?>`

Which produces:

5
• September 11, 2006 - Added solution 1.
© 2004-20 robson | cc unless stated