A
A
Allarion2017-05-29 18:04:44
PHP
Allarion, 2017-05-29 18:04:44

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
)

How can you check that the sequence of values ​​in ar matches $pattern and the order of values ​​in $arFail does not match $pattern?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2017-05-29
@Allarion

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;
}

E
egor_nullptr, 2017-05-29
@egor_nullptr

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 question

Ask a Question

731 491 924 answers to any question