我制作了这个代码来计算最大胜利和在一系列价值观上失去了条纹。但我可以在一个foreach循环中做到这一点。目前我正在使用2个循环:
public function calculateStreaks()
{
$max_win_streak = 0;
$_win_streak = 0;
$max_loss_streak = 0;
$_loss_streak = 0;
foreach($this->all_trades_pnl as $value){
if($value >= 0) {
$_win_streak++;
if($_win_streak > $max_win_streak){
$max_win_streak = $_win_streak;
}
}
else {
$_win_streak = 0;
}
}
foreach($this->all_trades_pnl as $value){
if($value < 0) {
$_loss_streak++;
if($_loss_streak > $max_loss_streak) {
$max_loss_streak = $_loss_streak;
}
}
else {
$_loss_streak = 0;
}
}
return array('win_streak' => $max_win_streak, 'loss_streak' => $max_loss_streak);
}
它有效,但似乎远未优化,任何想法更好地编码? 非常感谢提前, 问候, 约翰
答案 0 :(得分:2)
由于你的循环都是相同的,我认为你可以将它们混合起来并一次性分配所有变量
public function calculateStreaks()
{
$max_win_streak = 0;
$_win_streak = 0;
$max_loss_streak = 0;
$_loss_streak = 0;
foreach($this->all_trades_pnl as $value){
if($value >= 0) {
$_win_streak++;
if($_win_streak > $max_win_streak){
$max_win_streak = $_win_streak;
}
$_loss_streak = 0;
}
else if($value < 0) {
$_loss_streak++;
if($_loss_streak > $max_loss_streak) {
$max_loss_streak = $_loss_streak;
}
$_win_streak = 0;
}
}
return array('win_streak' => $max_win_streak, 'loss_streak' => $max_loss_streak);
}