Heim  >  Fragen und Antworten  >  Hauptteil

PHP-Array-Rotation

<p>Wie kann ich von diesen beiden Integer-Arrays feststellen, ob das zweite Array eine gedrehte Version des ersten Arrays ist und welche PHP-Funktion erforderlich ist? </p> <p>Beispiel: Ursprüngliches Array A=[1,2,3,4,5,6,7,8] Array drehen B=[6,7,8,1,2,3,4,5]</p> <p>In diesem Beispiel werden alle Zahlen in Array A um 5 Positionen nach rechts gedreht. </p>
P粉043295337P粉043295337385 Tage vor493

Antworte allen(1)Ich werde antworten

  • P粉111627787

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

    没有内置函数,但您可以旋转每个位置并比较是否正确。

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

    输出

    true
    false
    true

    Antwort
    0
  • StornierenAntwort