How to code this algorithm in PHP?
I have a complex algorithm that I try to code in PHP but it's a bit complicated for a beginner like me. So I need your help guys
I have an array of unknown numbers starting fron t1 up to tn. I don't know its length actually.like(t1,t2,t3,t4,.....,tn)
And I want to test a condition on the first elemnt if not, on the last element if not will test a common condition against the values from t2 to tn-1
I also have values called s , c & b that I will use in the code. The first condition is :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 non of the previous conditions were matched then I wanna test the values from t2 up to tn-1 in the following way
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
an开发者_C百科d so on up to tn-1 .. I don't know how many values there are in the array so i need to do this dynamically
Can any one help me ? It will be a great help indeed
Let's imagine for a moment this isn't your homework.
The first condition is boring, it's IF
statements with a check to make sure t2
exists and a count()
to find tn
. Second part is slightly more interesting:
$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;
}
Or something along those lines.
This is could be a kick start for you:
<?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;
}
}
?>
Try this:
$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);
Note that "$c >= $s" is not needed in the second "if" statement except for clarity.
精彩评论