Advertisement
Btwonu

arrayRotation

Jun 14th, 2020
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function arrayRotation(arr, rotations) {
  2.   //Number of rotations loop
  3.   for (let i = 0; i < rotations; i++) {
  4.     let firstElement = arr[0];
  5.  
  6.     //Move all elements to the left
  7.     for (let j = 0; j < arr.length - 1; j++) {
  8.       arr[j] = arr[j + 1];
  9.     }
  10.     //Set last element to the old first element
  11.     arr[arr.length - 1] = firstElement;
  12.   }
  13.  
  14.   //Stringify array
  15.   let arrayString = '';
  16.   for (let i = 0; i < arr.length; i++) {
  17.     if (i == arr.length - 1) {
  18.       arrayString += arr[i];
  19.     } else {
  20.       arrayString += arr[i] + ' ';
  21.     }
  22.   }
  23.  
  24.   //Output
  25.   console.log(arrayString);
  26. }
  27.  
  28. arrayRotation(
  29.   [51, 47, 32, 61, 21], 2
  30. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement