我想找到连续的匹配硬币面。我设法使它连续3个匹配的尾部将结束循环。
但是我怎么能包括头(它似乎忽略了头)?
例如:
0 is heads
reset
0 is heads
reset
1 is tails
1 is tails
1 is tails
total flips took is: 5
PHP:
$flipCounts = 0;
$matchingFaceTypes = 0;
$targetReached = false;
while ($matchingFaceTypes < 3 ) {
$faceType = rand(0, 1);
$flipCounts++;
if($faceType == 0) {
$matchingFaceTypes++;
echo $faceType . " is heads ". "\n";
}
if($faceType == 1) {
$matchingFaceTypes++;
echo $faceType." is tails ". "\n";
} else {
$matchingFaceTypes =0;
echo " reset ". "\n";
}
} echo "total flips took is: " . $flipCounts;
答案 0 :(得分:2)
$maxMatches = 3;
$matches = array('tails' => 0, 'heads' => 0, 'total' => 0);
while(max($matches['tails'], $matches['heads']) < $maxMatches) {
$faceType = rand(0, 1);
if ($faceType) {
$matches['heads']++;
$matches['tails'] = 0;
echo $faceType . " is heads\n";
}
else {
$matches['tails']++;
$matches['heads'] = 0;
echo $faceType . " is tails\n";
}
$matches['total']++;
}
echo "total flips took is: " . $matches['total'];
说到max()
$maxMatches = 3;
$total = 0;
$matches = array('tails' => 0, 'heads' => 0);
while(max($matches) < $maxMatches) {
$faceType = rand(0, 1);
if ($faceType) {
$matches['heads']++;
$matches['tails'] = 0;
echo $faceType . " is heads\n";
}
else {
$matches['tails']++;
$matches['heads'] = 0;
echo $faceType . " is tails\n";
}
$total++;
}
echo "total flips took is: " . $total;
答案 1 :(得分:1)
else指的是第二个if,所以如果$ facetype == 0
则会采用else下一个问题:您没有检查最后一个类型是否与之前的类型相同
我建议使用一个名为$lasttype
的变量并检查$faceType
是否等于该变量,如果没有重置计数器,则在此之后执行输出
$flipCounts = 0;
$matchingFaceTypes = 0;
$ctype=0;
$targetReached = false;
$lasttype=-1;
while ($matchingFaceTypes < 3 ) {
$faceType = rand(0, 1);
$flipCounts++;
if($faceType != $lasttype) {
if($lasttype!=-1)
echo " reset ". "\n<br/>";
$lasttype=$faceType;
$matchingFaceTypes =0;
}
if($faceType == 0) {
$matchingFaceTypes++;
echo $faceType . " is heads ". "\n<br/>";
}else{
$matchingFaceTypes++;
echo $faceType." is tails ". "\n<br/>";
}
}
echo "total flips took is: " . $flipCounts;