Reputation: 5374
I'm learning PHP and try to write a little dice loop. I wonder how to rewrite this in a more appropriate syntax:
<?php
$rollcount = 1;
do {
$v = rand(1, 6);
$w = rand(1, 6);
$rollcount++;
echo "<p>$v, $w</p>";
}
while ($v != $w);
if ($v == $w) {
echo "<p>It took $rollcount turns until double!</p>";
} else {}
?>
Upvotes: 0
Views: 1343
Reputation: 48031
Your choice to use do-while()
is appropriate because the $v
and $w
values are only declared after the loop is entered.
Because the loop will not finish until the values are identical, you don't need any conditions after the loop.
Your roll count should start from 0 outside of the loop because it is incremented inside of the loop.
Code: (Demo)
$rollcount = 0;
do {
$v = rand(1, 6);
$w = rand(1, 6);
echo "<p>$v, $w</p>";
++$rollcount;
} while ($v !== $w);
echo "<p>Rolls until a double: $rollcount</p>";
As an academic exercise, this task can be performed using recursion: (Demo)
function rollsUntilDouble($i = 1)
{
$v = rand(1, 6);
$w = rand(1, 6);
echo "<p>$v, $w</p>";
return $v === $w ? $i : rollsUntilDouble($i + 1);
}
printf('<p>Rolls until a double: %d</p>', rollsUntilDouble());
Upvotes: 0
Reputation: 1482
$rollcount = 0;
while(true){
++$rollcount;
$v = rand(1,6);
$w = rand(1,6);
echo "<p>".$v.", ".$w."</p>";
if($v === $w){
break;
}
}
echo "<p>It took ".$rollcount." turns until double!</p>";
Since the goal is to achieve a double, the dice can continue rolling till the condition is reached. while
continues processing until the condition is false, in this case the condition can never be false since we supply the boolean true
value to the while(true)
loop. PHP (and many other languages) provide some execution control structures break, continue
are the most common.
break
allows you to jump out of a loop and it's possible to execute it when a certain condition is reached within the loop.
continue
on the other hand doesn't throw you out of the loop rather, it skips to the next iteration of the loop, so what this means is that as soon as continue
is encountered in a loop, every other statement after it [within the loop] is skipped and the loop moves to the next iteration.
In this case, as soon as we have a double, we exit the loop and print out the number of rolls required to reach a double.
Upvotes: 3
Reputation: 30488
just remove else{}
if ($v == $w) {
echo "<p>It took $rollcount turns until double!</p>";
}
Upvotes: 2