rotateClockwise.js ( ***Please Revise***)
/*Rotate Array Clockwise
Write a function which takes an array arr and a postive integer m and rotates arr clockwise, m times.
Input
First line contains a sequence of integers separated by spaces, denoting arr
Second line contains a positive integer, denoting m
Output
Elements of the rotated array, one in each line
Example
Input:
2 1 3 4 5 10
1
Output:
10
2
1
3
4
5
Explanation
Given array is [2, 1, 3, 4, 5, 10]. m is 1, which means that the array needs to be rotated clockwise 1 time. One clockwise rotation means all the elements get shifted towards right by 1 position. The last element will get shifted to the first postion. So, the rotated array will be [10, 2, 1, 3, 4, 5].
*/
let fs = require("fs");
let data = fs.readFileSync(0, 'utf-8');
let idx = 0;
data = data.split('\n');
function readLine() {
idx++;
return data[idx - 1].trim();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
let arr = readLine().split(" "); // ["2","1","3","4","5","10"]
let m = parseInt(readLine()); //1
let i = 1
while (i <= m) // i=1 is <= 1 true, i=2 is <=1 false exit the whileloop
{
let secondarr = arr.pop(); // 10 ["2","1","3","4","5"]
//console.log(secondarr); // 10
arr.unshift(secondarr); // // ["10","2","1","3","4","5"]
i++ // 2
}
for (let i = 0; i < arr.length; i++) // 1.(i=0<6 true), 2.(i=1<6 true) ,3.(i=2<6 true), 4.(i=3<6), 5.(i=4<6), 6.(i=5<6 true)
{
console.log(arr[i]); // 1.10 2.2 3.1 4.3 5.4 6.5
}
//////////////////////////////////////////////////////////////////////////////////////////////

Comments
Post a Comment