Codility cyclic rotation solution in PHP











up vote
1
down vote

favorite
1












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
)









share|improve this question
























  • How about rotating the 4-element A array K=4 million times...?
    – CiaPan
    Mar 16 at 8:07










  • Welcome de CodeReview.SE! Please add a link to the original problem in your question.
    – Josay
    Mar 16 at 16:54















up vote
1
down vote

favorite
1












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
)









share|improve this question
























  • How about rotating the 4-element A array K=4 million times...?
    – CiaPan
    Mar 16 at 8:07










  • Welcome de CodeReview.SE! Please add a link to the original problem in your question.
    – Josay
    Mar 16 at 16:54













up vote
1
down vote

favorite
1









up vote
1
down vote

favorite
1






1





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
)









share|improve this question















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
)






php programming-challenge array






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 17 at 17:47









200_success

127k15149412




127k15149412










asked Mar 16 at 7:48









riser101

1133




1133












  • How about rotating the 4-element A array K=4 million times...?
    – CiaPan
    Mar 16 at 8:07










  • Welcome de CodeReview.SE! Please add a link to the original problem in your question.
    – Josay
    Mar 16 at 16:54


















  • How about rotating the 4-element A array K=4 million times...?
    – CiaPan
    Mar 16 at 8:07










  • Welcome de CodeReview.SE! Please add a link to the original problem in your question.
    – Josay
    Mar 16 at 16:54
















How about rotating the 4-element A array K=4 million times...?
– CiaPan
Mar 16 at 8:07




How about rotating the 4-element A array K=4 million times...?
– CiaPan
Mar 16 at 8:07












Welcome de CodeReview.SE! Please add a link to the original problem in your question.
– Josay
Mar 16 at 16:54




Welcome de CodeReview.SE! Please add a link to the original problem in your question.
– Josay
Mar 16 at 16:54










2 Answers
2






active

oldest

votes

















up vote
1
down vote













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.






share|improve this answer




























    up vote
    0
    down vote













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





    share|improve this answer





















      Your Answer





      StackExchange.ifUsing("editor", function () {
      return StackExchange.using("mathjaxEditing", function () {
      StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
      StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
      });
      });
      }, "mathjax-editing");

      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "196"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f189734%2fcodility-cyclic-rotation-solution-in-php%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote













      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.






      share|improve this answer

























        up vote
        1
        down vote













        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.






        share|improve this answer























          up vote
          1
          down vote










          up vote
          1
          down vote









          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.






          share|improve this answer












          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.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 17 at 16:23









          KIKO Software

          1,549512




          1,549512
























              up vote
              0
              down vote













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





              share|improve this answer

























                up vote
                0
                down vote













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





                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









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





                  share|improve this answer












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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 17 at 12:59









                  Joe Black

                  1663




                  1663






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Code Review Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      Use MathJax to format equations. MathJax reference.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f189734%2fcodility-cyclic-rotation-solution-in-php%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Morgemoulin

                      Scott Moir

                      Souastre