2017-07-14 68 views
3
$data = array(5,0,15,20,22,14,13,15,12,22,40,25); 

enter image description herePHP - 查找基於範圍

您好,我要遍歷上面的數據點,並找到基於一系列轉折點在陣列數據(高和低)的轉折點。

到目前爲止我處理它的方式是簡單地取$ array [$ i] - $ array [$ i-1],如果絕對差值大於範圍 - 我將它作爲轉折點 。然而 - 邏輯是有缺陷的,好像它略微上升然後回落 - 它打破了循環。

enter image description here

三個降值應該已經足以讓X,一個轉折向下,而是因爲他們單獨不符合範圍 - 他們被丟棄。

任何解決方案?

if($diff >= 0) 
{ 
    $diff_up = $diff_up + $diff; 
} 
else 
{ 
    $diff_down = $diff_down + abs($diff); 
} 


if((($diff_up-$diff_down) >=$range) && ($pivot_type != "UP")) 
{ 
    echo "Pivot UP at : ".$current; 
    break; 
} 
else if((($diff_down-$diff_up) >$range) && ($pivot_type != "DOWN")) 
{ 
    echo "Pivot DOWN at : ".$current; 
    break; 
} 
+1

莫非你更清楚地說明了「轉折點」的標準T「?你很可能需要一個稍微複雜的算法。 –

+1

在數組中,轉折點在哪裏?向我們展示一個預期的輸出數組 – Andreas

+0

@Kylon Tyner - 基本上圖形開始向上或向下移動的點,給定範圍例如:20 –

回答

0

你所尋找的是所有本地最小值和最大值,This is a good article

我做了這個(與靈感: get extremes from list of numbers):

<?php 
$data = array(5,0,15,20,22,14,13,15,12,22,40,25); 

function minima_and_maxima(array $array){ 
    $maxima = []; 
    $minima = []; 

    $maxima[] = $array[0]; 
    for($i = 1; $i < count($array) - 1; $i++){ 
    $more_than_last = $array[$i] > $array[$i-1]; 
    $more_than_next = $array[$i] > $array[$i+1]; 

    $next_is_equal = $array[$i] == $array[$i+1]; 

    if($next_is_equal) { 
     continue; 
    } 

    if ($i == 0) { 
     if ($more_than_next) { 
     $maxima[] = $array[$i]; 
     } else { 
     $minima[] = $array[$i]; 
     } 
    } elseif ($i == count($array)-1) { 
     if ($more_than_last) { 
     $maxima[] = $array[$i]; 
     } else { 
     $minima[] = $array[$i]; 
     } 
    } else { 
     if ($more_than_last && $more_than_next) { 
     $maxima[] = $array[$i]; 
     } elseif (!$more_than_last && !$more_than_next) { 
     $minima[] = $array[$i]; 
     } 
    } 
    } 

    for ($i = 0; $i < count($maxima); $i++) { 
    $current_maxima = $maxima[$i]; 
    $next_maxima = $maxima[$i+1]; 

    if ($current_maxima > $next_maxima) { 
     unset($maxima[$i+1]); 
    } 
    } 

    for ($i = 0; $i < count($minima); $i++) { 
    $current_minima = $minima[$i]; 
    $next_minima = $minima[$i+1]; 

    if ($next_minima < $current_minima) { 
     unset($minima[$i]); 
    } 
    } 

    return [ 
    'maxima' => array_values($maxima), 
    'minima' => array_values($minima), 
    ]; 
} 

function get_turning_points($data) 
{ 
    $mins_and_maxs = minima_and_maxima($data); 

    $turning_points = []; 
    for ($i = 0; $i < count($mins_and_maxs['maxima']) - 1; $i++) { 
    $turning_points[] = $mins_and_maxs['maxima'][$i]; 
    $turning_points[] = $mins_and_maxs['minima'][$i]; 
    } 
    $turning_points[] = $mins_and_maxs['maxima'][count($mins_and_maxs['maxima'])-1]; 

    return $turning_points; 
} 

print_r(get_turning_points($data)); 

這給了你:

Array 
(
    [0] => 5 
    [1] => 0 
    [2] => 22 
    [3] => 12 
    [4] => 40 
) 

演示:https://eval.in/832708

希望這有助於:)