To find the shortest distance between each number you just need to compare the number on which you go with the front number, and if it is larger than the calculated distance so far, update it.
Sequences already involve more complexity, but you can discover them by seeing if the distance to the front element is 1
and if it is added this element to an array, which in turn is added to another global array of sequences. The end of the current sequence occurs when the distance ceases to be 1
.
Example of implementation of this logic:
$a = array(1, 2, 4, 6, 8, 9, 10, 15, 16, 17, 20, 21, 23, 24, 26, 27, 28, 29, 31, 39);
$maiorDistancia = 0;
$sequencias = [];
$ultimaSeq = 0;
for ($i = 0; $i < count($a)-1; ++$i){
$dist = abs($a[$i]-$a[$i+1]); //distancia entre este e o proximo
if ($dist > $maiorDistancia) $maiorDistancia = $dist; //se maior atualiza
if (($a[$i+1]-$a[$i]) == 1){ //teste para sequencia
if (isset($sequencias[$ultimaSeq])){
$sequencias[$ultimaSeq][] = $a[$i+1]; //se ja existe uma sequencia acrescente
}
else { //se é uma nova insere os 2 primeiros elementos
$sequencias[$ultimaSeq][0] = $a[$i];
$sequencias[$ultimaSeq][1] = $a[$i+1];
}
}
else {
$ultimaSeq++;
}
}
Exit:
Maior distancia: 8
Sequencias: Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[3] => Array
(
[0] => 8
[1] => 9
[2] => 10
)
[4] => Array
(
[0] => 15
[1] => 16
[2] => 17
)
[5] => Array
(
[0] => 20
[1] => 21
)
[6] => Array
(
[0] => 23
[1] => 24
)
[7] => Array
(
[0] => 26
[1] => 27
[2] => 28
[3] => 29
)
)
Ideone with this solution
Notes:
- The solution only assumes increasing sequences, so if it is possible to have decreasing sequences it becomes necessary to make some adjustments to the code.
- The distance used was calculated based on the function
abs
, and so both contemplates positive and negative distances.
- The distance between
39
and 31
really is 8
, something the calculator can prove, but if you want to get the 7
because he wants to disregard his own 39
just need to subtract 1
.
O_O.. I don’t understand this logic :)
– Sam
What don’t you understand? Rs, it’s well explained. I want to know how many sequences there are (in my example would be 6 sequences) and I need to know the LONGEST distance between the numbers within the array (in my example 7).
– Thiago
Sorry, but it seems those problems of the magazine Super Interesting. For me it was not clear at all. Sorry the irony but I didn’t understand anything. rs.. If any other friend understands you may help you.
– Sam
I also understood paws.
– user60252