JavaScript Program to Generate all rotations of a number


We will generate all rotations of a number in JavaScript by converting the number into a string, then rotating the characters of the string, and finally converting it back into a number. This process will be repeated for each rotation. We will continuously repeat this process until we have generated all the possible rotations of the given number. This program will allow us to efficiently generate all rotations of a number and will be useful for various mathematical computations.

Approach

The approach to generate all rotations of a number in JavaScript is to convert the number to a string, split it into an array of characters, and then use a loop to iterate over the array and shift the first character to the end of the array at each iteration. The rotated array can be joined back to form a string and then converted back to a number. Repeat the process for the desired number of rotations. Here is the explanation −

  • Convert the number to a string to allow for string manipulation.

  • Split the string into an array of characters using the split method.

  • Initialize a loop to run for the desired number of rotations.

  • In each iteration, shift the first character of the array to the end using the shift and push array methods.

  • Join the rotated array back to a string using the join method.

  • Convert the string back to a number and store it in an array to collect all rotations.

Example

Here is a JavaScript program to generate all rotations of a given number −

function generateRotations(num) {
   let numStr = num.toString();
   let rotations = [];
     
   for (let i = 0; i < numStr.length; i++) {
      numStr = numStr.slice(1) + numStr[0];
      rotations.push(parseInt(numStr));
   }
     
   return rotations;
}
console.log(generateRotations(123));

Explanation

  • The generateRotations function takes in a number as a parameter.

  • The number is converted to a string and stored in the numStr variable.

  • A for loop is used to generate all the rotations of the number. The loop runs for numStr.length times, which is equal to the number of digits in the number.

  • In each iteration of the loop, the first digit of numStr is removed and added to the end of the string. This creates a new rotated version of the number.

  • The new rotated number is then parsed back to an integer and added to an array rotations.

  • After all the rotations have been generated, the rotations array is returned as the result.

  • The code is tested by calling the generateRotations function with the number 123 and printing the result to the console.

Updated on: 15-Mar-2023

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements