views:

210

answers:

2

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

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

what is the shortest code to do this?

+3  A: 

See the example for shuffle():

$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
    echo "$number ";
}
deceze
you need to s/20/100/
pavium
I was just copy'n'pasting from the manual. I'm leaving the customizations to the OP.
deceze
So he can fix the `echo` statement, too? ;-)
pavium
Yes he can. I think it's more important to convey the idea than copy'n'pastable solutions.
deceze
+1 for answering first and correctly. @pavium What is the point of giving people their entire programs? It's more important that the OP understands *what* is happening, and then applies it to his situation.
Josh Leitzel
+9  A: 

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.

Jonathan Fingland
A shorter way to say the same thing would be:foreach (shuffle(range(1,100)) as $num) echo 'h{'.$num.'}';
garethm
@garethm: No it wouldn't, since `shuffle` does not return the array.
deceze