This question is in regard to another question that was posted earlier by someone else:
PHP: Determining Grid Count Between 2 Grids.
Note: Understanding the above problem is not necessary for this question; I just wanted to provide it for reference and additional context.
I was able to solve the problem, but I don't like my solution - it is obviously repetitive and I know it can be simplified, but my brain is just too fried right now to see it. I just can't give in and go to bed until I get some resolution.
Here is my current, working solution (at least the part that is relative to my question):
// Note: $col_diff and $row_diff will always be integers between 0 and 4
if ($col_diff==4) {
$d = 5;
}
elseif ($col_diff==3) {
if ($row_diff==4)
$d = 5;
else
$d = 4;
}
elseif ($col_diff==2) {
if ($row_diff==4)
$d = 5;
elseif ($row_diff==3)
$d = 4;
else
$d = 3;
}
elseif ($col_diff==1) {
if ($row_diff==4)
$d = 5;
elseif ($row_diff==3)
$d = 4;
elseif ($row_diff==2)
$d = 3;
else
$d = 2;
}
elseif ($col_diff==0) {
if ($row_diff==4)
$d = 5;
elseif ($row_diff==3)
$d = 4;
elseif ($row_diff==2)
$d = 3;
elseif ($row_diff==1)
$d = 2;
else
$d = 1;
}
echo $d; // Correct!
How can I simplify this and remove the redundancy?
This is what I envision the optimized structure to look like, but it is obviously flawed:
for ($i=4;$i>=0;$i--)
if ($col_diff==$i)
for ($j=$i;$j>=0;$j--)
if ($row_diff==$j)
$d = $j+1;
echo $d; // NOT Correct!