Advertisement
Btwonu

rotateArray

Jun 14th, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. function rotateArray(arr) {
  4.   let rotations = Number( arr.pop() );
  5.   if ( isNaN(rotations) ) {
  6.     console.log('Empty');
  7.     return;
  8.   }
  9.  
  10.   //Rotations
  11.   for (let i = 0; i <= rotations - 1; i++) {
  12.     let lastElement = arr[arr.length - 1];
  13.  
  14.     //Move all elements to the right
  15.     for (let j = arr.length - 1; j >= 0; j--) {
  16.       arr[j] = arr[j - 1];
  17.     }
  18.       arr[0] = lastElement;
  19.      
  20.   }
  21.   console.log( arr.join(' ') );
  22. }
  23.  
  24. rotateArray(['remove', 'remove', 'remove']);
  25.  
  26. [1, 2, 3, 4]
  27.  
  28. [4, 1, 2, 3]
  29.  
  30. [3, 4, 1, 2]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement