这是我关于如何
calculate the longest undefeated streak的初步问题的后续跟进.
我修改了我的数据表,添加了一个“场地”栏,以显示游戏是“回家”还是“离开”:
date result venue ----------------------------- 1980-08-16 W H 1980-08-19 L A 1980-08-23 W A 1980-08-26 W H 1980-08-30 D H and so on...
由于我之前的问题,我已成功计算出最长的整体条纹,但现在我想根据场地来计算这些条纹并且我不确定如何去做.
例如,对于大多数家庭连续的主场胜利,我尝试了以下查询 – 但结果“运行”的返回时间比实际更短(基于数据的手动计数),并且没有明显的中断:
sql:
SELECT result,venue,MIN(date) as StartDate,MAX(date) as EndDate,COUNT(*) as Games FROM ( SELECT result,date,( SELECT COUNT(*) FROM resultengine R WHERE R.result <> RE.result AND (R.venue = 'H') <> (RE.venue = 'H') AND R.date <= RE.date ) as RunGroup FROM resultengine RE ) A WHERE venue = 'H' AND result='W' GROUP BY result,RunGroup ORDER BY Games
PHP:
$result = MysqL_query( /* the sql statement from above */ ); while($row=MysqL_fetch_assoc($result)) { $startrundate = date("d F Y",strtotime($row['StartDate'])); $endrundate = date("d F Y",strtotime($row['EndDate'])); echo "<tr>"; echo "<td>".$row['Games']."</td>"; echo "<td class='tableprofile' style='text-align:right;'>".$startrundate." - ".$endrundate."</td>"; echo "</tr>"; $rowCount += 1; }
事实证明这比我想象的要困难,但同样不相信我离解决方案太远了.它只是弥合了我所拥有的和我目前没有做的事情之间的差距.
UPDATE
我似乎已经解决了这个特殊问题.它就像更改子句(R.venue =’H’)<>一样简单(RE.venue =’H’)到R.venue = RE.venue
以下忽略任何sql并假设您只有一个“游戏”列表,并且您想要计算出最长的条纹.在这种情况下,我假设“游戏”是一个方法isWon()的类.
$currentStreak = 0; $longestString = 0; foreach($games as $game) { if(!$game->wasWon()) { $currentStreak = 0; continue; } $currentStreak++; if($currentStreak > $longestStreak) { $longestStreak = $currentStreak; } }
如果你想扩展逻辑只关心主游戏,你可以包装整个逻辑:
foreach($games as $game) { if($game->wasHomeGame()) { if(!$game->wasWon()) { $currentStreak = 0; continue; } $currentStreak++; if($currentStreak > $longestStreak) { $longestStreak = $currentStreak; } } }
这样可以更好地放置在具有更大灵活性的类中,例如,您可以使用值类来说明播放的位置:
public function getLongestStreak(array $games,Venue $venue) { $currentStreak = 0; $longestString = 0; foreach($games as $game) { if($game instanceof Game && $game->wasPlayedAt($venue)) { if(!$game->wasWon()) { $currentStreak = 0; continue; } $currentStreak++; if($currentStreak > $longestStreak) { $longestStreak = $currentStreak; } } } return $longestStreak; }
我可以继续描述价值课程如何在这里工作,但我只是分散了工作的注意力,希望我已经解决了你的问题. 原文链接:https://www.f2er.com/php/134066.html