/*
[1, 2, 3, 4]
length: 4
V(K % length) index value answer
1 0 N[3] (index + length -1 * V) % length
1 1 N[0]
1 2 N[1]
1 3 N[2]
2 0 N[2] (index + length -1 * V) % length
2 1 N[3]
2 2 N[0]
2 3 N[1]
...
*/
function solution(A, K) {
const V = K % A.length;
const answer = A.map(
(_, index) => A[(index + (A.length - 1) * V) % A.length],
);
return answer;
}
https://gist.github.com/doong-jo/197d6fe48697fed16bc5d95ae60244cd
/**
* Rotate array
* @param {number[]} A target number array (ex. [1, 2, 3, 4])
* @param {number} K rotate count
* @param {number} D rotate distance
*/
function rotateArray(A, K, D = 1) {
const V = ((A.length - D) * K) % A.length;
return A.map((_, index) => A[(index + V) % A.length]);
}
const r1 = rotateArray([1, 2, 3, 4], 1, 1);
const r2 = rotateArray([1, 2, 3, 4], 2, 4);
const r3 = rotateArray([1, 2, 3, 4], 1, 2);
const r4 = rotateArray([1, 2, 3, 4], 1, 4);
console.log(r1); // [ 4, 1, 2, 3 ]
console.log(r2); // [ 1, 2, 3, 4 ]
console.log(r3); // [ 3, 4, 1, 2 ]
console.log(r4); // [ 1, 2, 3, 4 ]