In the past, I ran into a problem when I had to write a verification algorithm for ranges created by the user (integers or numbers). I had to check 3 things:
- Ranges continuous
- Ranges do not overlap
- LOW must always be <= than HIGH
So, I came up with the following PHP algorithm.
//Let hardcode an array of integers (it can be of reals as well): $range = array ( array(1, 13), array(14, 20), array(21, 45), array(46, 50), array(51, 60) ); //And the validation algorithm: $j = 0; $rows = sizeof($range); $step = 1; // This indicates the step of the values. // 1 for integers, 0.1 or 0.01 for reals for ($x=0; $x<$rows; $x++) for ($y=0; $y<$rows; $y++) { if ( ($range[$x][0] <= $range[$y][0]) AND ($range[$y][0] <= $range[$x][1]) AND ($x != $y) ) { echo "Ranges intercepting"; // replace with error handling code break 3; } if ( $range[$x][0] > $range[$x][1] ) { echo "Not valid high & low"; // replace with error handling code break 3; } if ( $range[$x][0] - $range[$y][1] == $step ) { $j++; } } if ( $j != $rows - $step ) echo "Not continuous"; // replace with error handling code
We iterate over the ranges and compare them in pairs. For each pair we have:
- find overlapping ranges and raise the error.
- find the start and end points in reverse order and raise the error.
If none of the above happens, we take into account the difference in the start points. This number should be equal to the number of ranges minus the step (1, 0.1, 0.01, etc.). Otherwise, we cause an error.
Hope this helps!
source share