2
\$\begingroup\$

Problem statement

A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place.

For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes.

My Solution

function solution($A, $K) {
   // when array is empty or has only one element 
   if(count($A) == 0 || count($A) == 1){
        return $A;
    }
    //runs k times
    for($j=1; $j<=$K; $j++){
        $last_element = $A[count($A)-1];
        //runs for each element
        for($i=(count($A)-1); $i>0; $i--){
            $A[$i] = $A[$i-1];
        }
        $A[0] = $last_element;  
    }
    return $A;
}

$A = [1, 2, 3, 4];
$K = 4;
$result = solution($A, $K);
print_r($result);

Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
\$\endgroup\$
  • \$\begingroup\$ How about rotating the 4-element A array K=4 million times...? \$\endgroup\$ – CiaPan Mar 16 '18 at 8:07
  • \$\begingroup\$ Welcome de CodeReview.SE! Please add a link to the original problem in your question. \$\endgroup\$ – SylvainD Mar 16 '18 at 16:54
2
\$\begingroup\$

You could use array functions. They simplify and speed up the handling of arrays. See: http://php.net/manual/en/ref.array.php

So your code could become:

function rotateArray($inputArray,$rightShiftCount)
// shift all elements of the array to the right a number of times
{
  // extract the part of the array to move to the front
  $partToMove = array_splice($inputArray,-($rightShiftCount % count($inputArray)));
  // return extract part followed by what was left of the array
  return array_merge($partToMove,$inputArray);
}

This function does not check its arguments, if needed you can add that.

Notice that I have used sensible names for my variables instead of $A and $K. This is intentional.

\$\endgroup\$
1
\$\begingroup\$

Actually, you don't need to rotate the initial array K times:

<?php

function solution($A, $K)
{
    // when array is empty or has only one element 
    if (count($A) == 0 || count($A) == 1) {
        return $A;
    }

    // The number of rotations needed
    $rotateTimes = $K % count($A);

    //runs `$rotateTimes` times
    for ($j = 1; $j <= $rotateTimes; $j++) {
        $last_element = $A[count($A) - 1];
        //runs for each element
        for ($i = (count($A) - 1); $i > 0; $i--) {
            $A[$i] = $A[$i - 1];
        }
        $A[0] = $last_element;
    }
    return $A;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.