Wow... they teach using PHP in school/college?
I'm in high school myself and my programming classes were boring :-)
Anyway, here is one way to do it:
<?php
// call srand so we get different random #s each time
srand(time());
// First generate the random numbers and put them in a sparse array. I don't know if it called "sparse array" but my definition of a sparse array is: an array in which the elements are not successive. Meaning it will have $array[1], $array[4], but NOT $array[3] or $array[2];
// So let's create a sparse array
for($i = 0; $i < 20; $i++) {
$myArray[getRandom($myArray)] = 1;
}
// here is the function getRandom
function getRandom(&$arrayPointer) {
$num = rand(0, 100);
for($i = 0; $i < 100; $i++) {
// this will check whether the random # already exists
if(($arrayPointer[$i]) && ($i == $num)) {
getRandom($arrayPointer);
return;
}
}
//okay not in array, so let's return the value
return $num;
}
// now we have a sparse array with 20 elements all having the value 1. We'll convert this to a sequential array with the element values containing the random #
$counter = 0;
for($i = 0; $i < 100; $i++) {
if($myArray[$i] == 1) {
$newArray[$counter] = $i;
$counter++;
}
}
// we're done... let's print out the contents to see if it worked
for($i = 0; $i < 20; $i++) {
print $newArray[$i] . "<br>\n";
}
?>
I've put this script up in my domain. Check it out:
http://www.theslinky.com/randnums.php
visit
http://www.theslinky.com/randnums.phps to see the source (same as above but more colorful)
like I said: that was one way of doing it. There are probably better ways to implement the same idea, so if your professor is really strict, try looking for alternate ways before using the above.
hope this helps!
-sridhar