Finding longest sequence in a set of numbers
September 2, 2006 12:01 AM
Subscribe
I have a question about finding the longest sequence in a set of numbers.
I have a database with a column containing numeric (integer) serial numbers. There are lots of gaps, and I'd like to find the longest sequence of sequential numbers in the set.
This possibly laughable bit of PHP code below is how I would approach it. (There is some error checking missing from it in the name of clarity as well as checking "isset()" and other niceties.)
// $query = returned database results
// $tempLow = scratch field for start of current sequence
// $low = final sequential set's start
// $high = final sequential set's end
$low = $query[0];
$high = $query[0];
$tempLow = $query[0];
for ($a=1; $a > count($query); $a++) {
` if ( $query[$a] > $query[$a - 1] + 1 ) {
`` if ( ( $high - $low ) < ( $query[$a - 1] - $tempLow ) ) {
``` $high = $query[$a - 1];
``` $low = $tempLow;
`` }
`` $tempLow = $query[$a];
` }
}
Is there a better way? This obviously only returns the first occurence of the longest sequence if there is more than one sequence of that length, which is OK.
posted by maxwelton to computers & internet (13 comments total)
2 users marked this as a favorite
posted by grouse at 2:14 AM on September 2, 2006