Cyclically rotate an array

"Cyclically rotate an array by one" is a task that involves shifting the elements of an array in a circular manner by one position to the right. This means that the last element of the array will move to the first position, and all other elements will shift to the right, with the original first element becoming the second, the second becoming the third, and so on.

Here's a detailed explanation of the task:

  1. Given an array [1, 2, 3, 4, 5], the goal is to cyclically rotate the elements by one position.
  2. After the rotation, the array should become [5, 1, 2, 3, 4].
  3. The last element, 5, moves to the first position, and all other elements shift one position to the right.
  4. The original first element, 1, moves to the second position, 2 moves to the third position, and so on.
  5. The original last element, 4, moves to the second-to-last position.

Now let's consider a real-world scenario to understand this task:

Imagine a group of friends sitting in a circle and playing a game. Each person represents an element in the array, and they need to pass an object around the circle, rotating it to the right after each pass.

Initially, the circle looks like this:

JavaScript
[Person 1, Person 2, Person 3, Person 4, Person 5]
// My Code Looks Like 
function cyclingAnArray(arr,n) {
  const lastElement = arr[arr.length - 1];
  n=lastElement;

  for (let i = arr.length - 1; i > 0; i--) {
    arr[i] = arr[i - 1];
  }
  arr[0] = n;
  return arr;
}
let array = [1, 2, 3, 4, 5];
console.log(cyclingAnArray(array));

Comments