is there way track continuous number subsequences in mysql?
i want count highest continuous subsequences in sequence of numbers:
1,2,3,4,6,7 => 4 (1-4) 1,2,3,4,5,6,8 => 6 (1-6) 1,2,3,5 => 3 (1-3) 1,2,3,5,6,7,8 => 4 (5-8) 1,2,4,5,6,8,9 => 3 (4-6)
according question code should work:
function findhighestseriescount( $seriesarray ) { if ( 1 >= count( $seriesarray ) ) { # catch special case when array has 0 or 1 element return count( $seriesarray ); } $highestcount = -1; $currentcount = 1; $lastelement = $seriesarray [0]; $getcorrecthighvalue = function() use ( &$highestcount, &$currentcount ) { return $highestcount < $currentcount ? $currentcount : $highestcount; }; ( $arrayindex = 1 ; $arrayindex < count( $seriesarray ) ; $arrayindex++ ) { if ( $lastelement + 1 == $seriesarray [$arrayindex] ) { $currentcount++; } else { $highestcount = $getcorrecthighvalue(); $currentcount = 1; } $lastelement = $seriesarray [$arrayindex]; } return $getcorrecthighvalue(); }
test script:
$seriesarray = [1,2,3,4,6,7]; echo sprintf( "array=%s - highest count=%d<br>", implode( ",", $seriesarray ), findhighestseriescount( $seriesarray ) ); $seriesarray = [1,2,3,4,5,6,8]; echo sprintf( "array=%s - highest count=%d<br>", implode( ",", $seriesarray ), findhighestseriescount( $seriesarray ) ); $seriesarray = [1,2,3,5]; echo sprintf( "array=%s - highest count=%d<br>", implode( ",", $seriesarray ), findhighestseriescount( $seriesarray ) ); $seriesarray = [1,2,3,5,6,7,8]; echo sprintf( "array=%s - highest count=%d<br>", implode( ",", $seriesarray ), findhighestseriescount( $seriesarray ) ); $seriesarray = [1,2,4,5,6,8,9]; echo sprintf( "array=%s - highest count=%d<br>", implode( ",", $seriesarray ), findhighestseriescount( $seriesarray ) );
output:
array=1,2,3,4,6,7 - highest count=4 array=1,2,3,4,5,6,8 - highest count=6 array=1,2,3,5 - highest count=3 array=1,2,3,5,6,7,8 - highest count=4 array=1,2,4,5,6,8,9 - highest count=3