Advertisement
AtanasStoyanov

Sirma Academy - Arrays - 11. Rotate Array (recursion)

May 24th, 2024 (edited)
371
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function rotate(arr) {
  2.   const arrLength = arr.length;
  3.   const lastElement = arr[arrLength - 1];
  4.   for (let index = arrLength - 1; index > 0; index--) {
  5.     arr[index] = arr[index - 1];
  6.   }
  7.   arr[0] = lastElement;
  8. }
  9.  
  10. function rotateArray(arr, rotations) {
  11.   for (let i = 0; i < rotations; i++) {
  12.     rotate(arr);    
  13.   }
  14.   console.log(arr.join(" "));
  15. }
  16.  
  17. rotateArray(['1', '2', '3', '4'], 2);
  18. rotateArray(['Banana', 'Orange', 'Coconut', 'Apple'], 15);
  19.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement