0

I have a unordered array of numbers:

$ar1 = [101,4,320,1,2,3,45,46];

and i want to extract longest sequence of numbers in that array and put them in second array? I have tried with usort and I get this:

Array(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 45
[5] => 46
[6] => 101
[7] => 320
[8] => 321
[9] => 323)

but how to extract just longest sequence (witch in this case is 1,2,3,4) and put in another array?

UPDATE: Here is a code:

function sub($a,$b)
{
if ($a == $b)
{
    return 0;
}
return ($a<$b)? -1:1;
}

$ar1 = ["101","4","320","321","323","1","3","2","45","46"];
$ar2 = [];
usort($ar1,"sub");
print_r($ar1);

so i want to populate $ar2 with longest sequence in array...

4
  • What would the expected output be? Commented Mar 17, 2015 at 15:03
  • Possible duplicate of this Commented Mar 17, 2015 at 15:05
  • just [1,2,3,4] in array Commented Mar 17, 2015 at 15:05
  • 3
    My initial thought would be, you are going to have to write some code Commented Mar 17, 2015 at 15:07

1 Answer 1

0

I got it:

$ar1 = [101,4,320,1,2,3,45,46,47];
sort($ar1);
$first = $ar1[0];//assign first (lowest) number
$i=0;
$ar2 = array(); //this array will contain all arrays of consecutive numbers
foreach($ar1 as $v){
    if($v-$first == 1){
        $ar2[$i][] = $v;
    }else{
        $i++;
        $ar2[$i] = array($v); //difference > 1, we set another array
    }
    $first = $v;
}
//now we look for the longest array
$max = 0;
$longest = array();
foreach($ar2 as $k=>$ar){
    $c = count($ar);
    if($c < $max){
        unset($ar2[$k]); //if it is not the longest, we discard it
    }else{
        $max = $c;
        $longest = $ar;
    }
}
echo"<pre>";
print_r($longest);
echo"</pre>";

Yields:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )

Copy, paste, run, enjoy!

Sign up to request clarification or add additional context in comments.

2 Comments

I'm happy then. Will be even happier when you accept my answer :)
Thanks, also change the title - it is not extrapolation in mathematic meaning. And change whont to want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.