开发者

PHP Random Numbers

i need to print out numbers 1-100 in a random order. the print statement should be:

echo 'h{'.$num.'}';

what is the shortest cod开发者_StackOverflow社区e to do this?


The easiest way is to use shuffle with an array containing the 100 numbers

e.g.

$sequence = range(1, 100);
shuffle($sequence);
foreach ($sequence as $num) {
    echo 'h{'.$num.'}';
}

Also see the range function

EDIT

I thought I might add a little on what shuffle does. Although php.net doesn't explicitly say so, it is likely based on the modern version of the Fisher-Yates shuffle algorithm. For a video demonstration of how it works, see http://www.youtube.com/watch?v=Ckh2DJrP7F4. Also see this excellent flash demonstration

The shuffle algorithm essentially works like this:

  1. For a given set of elements A1 to AN, and n = N;
  2. Randomly select an element Ak between A1 and An inclusive
  3. Swap Ak and An
  4. Set n = n - 1
  5. Repeat from step 2

Hope that helps.


See the example for shuffle():

$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
    echo "$number ";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜