首頁  >  問答  >  主體

php 陣列旋轉

<p>在這兩個整數陣列中,如何確定第二個陣列是否是第一個陣列的旋轉版本以及需要哪個 php 函數? </p> <p>範例: 原始數組 A=[1,2,3,4,5,6,7,8] 旋轉數組 B=[6,7,8,1,2,3,4,5]</p> <p>在此範例中,陣列 A 的所有數字都向右旋轉 5 個位置。 </p>
P粉043295337P粉043295337385 天前492

全部回覆(1)我來回復

  • 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

    回覆
    0
  • 取消回覆