Generate random numbers between 1-100 and stop when it hits 99 and count the amount of attepmts it took

1.1k views Asked by At

Im currently working on something that i really need help with. Im gonna make a while or do while loop that with the rand fuction generates random numbers between 1 and 100. When the random numbers hits 99 the loop should stop and the show the amount of attempts it took to hit the number 99 like this:

"It took 53 attempts to hit the number 99"

If someone could help me with a simple solution I would be so grateful!

3

There are 3 answers

4
Professor Abronsius On

A simple loop like this ought to do what you are after

$count=0;
$i=0;
$target=99;

while( $i!=$target ){
    $i=rand(1,100);
    $count++;
}
printf('it took %u attempts to reach %u',$count,$target);
0
Dipak On

In my code, I declare flag variable have value true. While loop will continue and add push value in $arrRandNum, until random value is 99.

Once 99 generates it sets flag value as false and loop will terminate.

<?php
    $flag = true;
    $randNum;
    $arrRandNum = array();
    while($flag){

        $randNum = rand(1,100);
        if(99 !== $randNum){
            array_push($arrRandNum,$randNum);
        }else{
            $flag = false;
        }
    }
    print_r("total attempts: ".count($arrRandNum)."<br/>");
    print_r($arrRandNum);
?>
0
Nigel Alderton On

A for loop is fine for this;

for ($count = 1; rand(1, 100) != 99; $count++);
echo "It took {$count} attempts to hit the number 99";

Example output;

It took 47 attempts to hit the number 99