2010-01-31 49 views
0

我有一個複雜的算法,我嘗試在PHP中進行編碼,但對於像我這樣的初學者來說,這有點複雜。所以我需要你的幫助
我有一個數組未知的數字從t1開始到tn。我不知道它的長度actually.like
如何在PHP中對此算法進行編碼?

(t1,t2,t3,t4,.....,tn) 

而且我想在第一elemnt如果沒有測試條件,最後一個元素上如果不將測試對價值的共同條件從T2到TN -1
我也有值,稱爲s,c & b,我將在代碼中使用。
第一個條件是:

if c < s -> Do something 
if c >= s and c < (s + (t1 - t2)) -> Do something else 
if c >= (s + (t1 - tn)) and c < (s + (t1 + b)) -> Do something else 

如果上述條件不相匹配,然後我想以下列方式

if c >= (s + (t1 - t2)) and c < (s + (t1 - t3)) -> Do something that's bound to t2 value 
if c >= (s + (t1 - t3)) and c < (s + (t1 - t4)) -> Do somehting else 

等測試來自T2了值TN-1上至tn-1 ..我不知道陣列中有多少值,所以我需要動態執行此操作

任何人都可以幫助我嗎?這將是一個很大的幫助確實

回答

1

讓我們想象一下,這不是你的家庭作業。

第一個條件是枯燥的,它的IF語句以檢查,以確保t2存在和count()找到tn。第二部分稍微有趣:

$homework = array(t1,t2....tn); 

for (
    $i=2,$n=count($homework),$cs=$c-$s,$cnd_a=$homework[0]-$homework[1];   
    $i<$n;++$i) 
{ 
    $cnd_b = $homework[0] - $homework[$i]; 
    if ($cs >= $cnd_a && $cs < $cnd_b) do_no_study($homework[$i-1]); 
    $cnd_a = $cnd_b; 
} 

或者沿着這些線。

0

這可能是爲你揭開序幕:

<?php 

function check_condition($value, $pos) 
{ 
    // do your magic 
    return TRUE; // or FALSE; 
} 

$values = array(1,2,3,4,5,6,7,8,9); 

// Array length 
$arr_length = length($values); 

// Check the first condition 
for ($i=0; $i<($arr_length/2); $i++) 
{ 
    if (check_condition($values[$i], $i)) 
    { 
     echo "condition met at start"; 
     break; 
    } 
    if (check_condition($values[$i], $arr_length-$i)) 
    { 
     echo "condition met at start"; 
     break; 
    } 
} 

?> 
0

試試這個:

$t = array(); // your array 
$len = count($t); 

if ($c < $s) 
    Do_something(); 
else if ($c >= $s && $c < ($s + ($t[0] - $t[1]))) 
    Do_something_else(); 
else if ($c >= ($s + ($t[0] - $t[$len - 1])) && $c < ($s + ($t[0] + b))) 
    Do_something_else_again(); 
else 
    for ($i = 1; $i < $len - 1; $i++) 
     if ($c >= ($s + ($[0] - $t[$i])) && $c < ($s + ($t[0] - $t[$i + 1))) 
      Do_something_thats_bound_to_value($t, $i); 

注意, 「$ C> = $ s」 不是在第二個「if」聲明中需要,除了清晰。

相關問題