I am trying to get a program to reiterate until both the $heads variable and $tails variable is greater than 0. I can't figure out what I am doing wrong. The while loop always gets broken after just one iteration.
<?php
echo "<table border=\"1\">";
echo "<tr><td>Person</td><td>Heads</td><td>Tails</td><td>Total</td></tr>";
for ($person=1; $person < 11; $person++){
echo "<tr><td>Person $person </td>";
$both = 0;
$heads = 0;
$tails = 0;
$total = 0;
while ($both < 1){
do {
$total++;
$random = rand(1,2);
if ($random == 1){
$heads++;
} else{
$tails++;
}
} while (($tails < 0) && ($heads < 0));
$both = 1;
}
echo "<td>$heads</td><td>$tails</td><td>$total</td>";
echo "</tr>";
}
echo "</table>";
?>
In this line
} while (($tails < 0) && ($heads < 0));
it appears that neither $tails
nor $heads
will ever be strictly less than 0
, so that will always be false. Try <= 0
for both.
Also, logically, you want to loop again if either of those conditions is true, right? So use ||
instead of &&
.
Result:
} while (($tails <= 0) || ($heads <= 0));
Also, I'm a little curious about the while ($both < 1)
loop. It appears that you assign $both = 0
before the loop, and you assign $both = 1
at the end of its iteration. That would guarantee the loop is only executed once, in which case -- what's the point of having that loop? Perhaps that's just unfinished code at this point?
So you want to keep flipping coins until you get at least one head and at least one tail result? And at the same time keep track of how many times you flipped?
I would have coded like this:
$heads = 0;
$tails = 0;
$total = 0;
while( true ) {
$total ++;
$random = rand( 0, 1 ); // 0 for tail, 1 for head
if( $random ) $heads ++;
else $tails ++;
if( $heads >= 1 && $tails >= 1 ) break;
}
The while loop will continue to run infinitely until both $heads and $tails become one or greater.