1
I have the following function:
function qa($array = array()) {
$a = $array;
$sequencias = [];
$ultima_seq = 0;
for ($i = 0; $i < count($a)-1; ++$i) {
if (($a[$i+1]-$a[$i]) == 1) {
if (isset($sequencias[$ultima_seq])) {
$sequencias[$ultima_seq][] = $a[$i+1];
} else {
$sequencias[$ultima_seq][0] = $a[$i];
$sequencias[$ultima_seq][1] = $a[$i+1];
}
} else {
$ultima_seq++;
}
}
$total_sequencia = count($sequencias);
return $total_sequencia;
}
It counts the numeric sequence blocks of an array, for example:
$a = array(1,2,4,5,7,8);
$b = array(10,11,12,15,16,20,21,22,30,31,32);
- In $to we have 3 sequences blocks (1,2 - 4,5 - 7,8);
- In $b we have 4 sequences blocks (10,11,12 - 15,16 - 20,21,22 - 30,31,32);
For example, we will use the following array`s:
$a_1 = array(1,2,3,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21);
$a_1_copia = array(01,02,03,04,05,06,07,08,09,10,11,12,13,15,16,17,18,19,20,21);
$a_2 = array(1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,20,21);
$a_2_copia = array(01,02,03,04,05,06,07,08,09,10,11,12,14,15,16,17,18,19,20,21);
$a_3 = array(1,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21);
$a_3_copia = array(01,02,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21);
The feedback I’m getting is this::
print_r(qa($a_1)); // 2
print_r(qa($a_1_copia)); // 3
print_r(qa($a_2)); // 2
print_r(qa($a_2_copia)); // 3
print_r(qa($a_3)); // 2
print_r(qa($a_3_copia)); // 3
However, all array’s have sequence 2. Those who are returning me 3 are like this if I use 0 (zero) in its tens.
I’ve broken my head, but I’m missing something. Where I’m going wrong here?
Is the goal to count the number of sequences contained in an array? Because some arrays have numbers starting at
0
, as an example(01,02,...
?– Isac
@Isac the goal is to count the amount of blocks sequences, as I explained above. Some arrays have
0
because I put to show the mistake I’m having.– Thiago
Your code seems correct to me, except for the zeros on the left. See here the result
– Isac
@Isac the code works perfectly when the array does not have
0
left. But the question is exactly this, how could it function properly when there is also0
to the left?– Thiago
For the simple fact that when a number has zero on the left PHP will consider it as base 8, an octal. Being octal, the values
08
and09
nor would they be valid numbers for PHP 7+; if it is already running in previous versions, PHP converts them to zero (because for PHP this makes sense).– Woss
I don’t understand why zeroes. Why do you have zeros? You’re interpreting from text ? If so, you should use
intval
to interpret the string as an integer that alone solves the problem– Isac
for is like ++$i , it shouldn’t be $i++ ?
– Claytinho