search

Home  >  Q&A  >  body text

php array rotation

<p>Of these two integer arrays, how do I determine if the second array is a rotated version of the first array and which php function is required? </p> <p>Example: Original array A=[1,2,3,4,5,6,7,8] Rotate array B=[6,7,8,1,2,3,4,5]</p> <p>In this example, all numbers in array A are rotated 5 positions to the right. </p>
P粉043295337P粉043295337477 days ago597

reply all(1)I'll reply

  • P粉111627787

    P粉1116277872023-09-04 00:34:22

    There is no built-in function, but you can rotate each position and compare whether it is correct.

    $isRotated = function (array $original, array $maybeRotated): bool {
        $originalCount     = count($original);
        $maybeRotatedCount = count($maybeRotated);
        if ($originalCount !== $maybeRotatedCount || $original === $maybeRotated) {
            return false;
        }
    
        for ($i = 0; $i < $originalCount; $i++) {
            $original[] = array_shift($original);
            if ($original === $maybeRotated) {
                return true;
            }
        }
    
        return false;
    };
    
    echo $isRotated([1, 2, 3, 4, 5, 6, 7, 8], [6, 7, 8, 1, 2, 3, 4, 5]) ? 'true' : 'false', PHP_EOL;
    echo $isRotated([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8]) ? 'true' : 'false', PHP_EOL;
    echo $isRotated([1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7, 8, 1]) ? 'true' : 'false', PHP_EOL;

    Output

    true
    false
    true

    reply
    0
  • Cancelreply