-2

In these 2 integer arrays, how can you determine if the 2nd array is a rotated version of the 1st array and which php function is needed?

Example: Original Array A=[1,2,3,4,5,6,7,8] Rotated Array B=[6,7,8,1,2,3,4,5]

In this example, all numbers of Array A are rotated to the right by 5 positions.

  • 1
    I'd probably approach the problem by checking that both arrays have the same values present (array intersect), then a few iterations (limited by number of items present) of moving a key from the start to the end and seeing if they match Leverage something like this https://stackoverflow.com/questions/5601707/rotate-array-elements-to-the-left-move-first-element-to-last-and-re-index – Scuzzy Nov 03 '22 at 21:09
  • There's nothing built-in that will do this. Write a function that rotates an array, then write a loop that compares `A` with every possible rotation of `B`. You can optimize this by finding the indexes of `A[0]` in `B`, and only testing those rotations. – Barmar Nov 03 '22 at 21:09
  • @MIR are you seeking a true/false result or 5? Also related: [Right rotation on array in php](https://stackoverflow.com/q/63180377/2943403) – mickmackusa Nov 03 '22 at 21:51
  • Do the two arrays always have the same size? Are they guaranteed to have the same values? There are too many edge cases to consider. Please explain your scenario more fully with an [edit]. – mickmackusa Nov 04 '22 at 00:04

1 Answers1

1

There's no built in function, but you can rotate for each position and compare if it is true.

$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
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35