Answer the question
In order to leave comments, you need to log in
Checking the correctness of the sequence in arrays in php?
There are two arrays 1 - a one-dimensional array, the correctness of the sequence of elements in which you need to check, and 2 - a one-dimensional array, a stencil, in which the correct sequence of elements is indicated. It would be easy to solve this issue if the number of elements were equal to each other, but array 1 may not contain all the values from array 2, but only a part of it.
Let's take arrays as an example:
$ar = array(
[0] => FIRST
[1] => SECOND
[2] => FIFTH
[3] => SEVENTH
[4] => EIGHTH
)
$pattern = array(
[0] => FIRST
[1] => SECOND
[2] => THIRD
[3] => FOURTH
[4] => FIFTH
[5] => SIXTH
[6] => SEVENTH
[7] => EIGHTH
[8] => NINTH
[9] => TENTH
)
$arFail = array(
[0] => EIGHTH
[1] => SEVENTH
[2] => FOURTH
[3] => SECOND
[4] => FIRST
)
Answer the question
In order to leave comments, you need to log in
Something like this:
function myCheck($arr, $pattern) {
$lastPos = -1;
foreach($arr as $value) { // перебираем массив
$pos = array_search($value, $pattern); // ищем текущий элемент в pattern
if ($pos !== false && $pos > $lastPos) { // если он найден, и позиция больше чем у предыдущего - все норм.
$lastPos = $pos;
} else return false; // если нет - не норм.
}
return true;
}
function check(array $p, array $a)
{
$stack = new SplStack();
foreach (array_reverse($a) as $i) {
$stack->push($i);
}
$top = $stack->pop();
foreach ($p as $i) {
if ($i == $top) {
if ($stack->isEmpty()) {
return true;
}
$top = $stack->pop();
}
}
return $stack->isEmpty();
}
assert(check($pattern, $ar));
assert(!check($pattern, $arFail));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question