[Codility Lessons] 2. Arrays - CyclicRotation

doongdoong·2020년 10월 9일
0

Codility Lessons

목록 보기
2/5

풀이

  • 배열 요소 접근에 대한 이해, 수학적 규칙을 찾아내면 식으로 풀 수 있다.
  • 정확도만 중요하다면 뒤에 맨 앞의 요소를 push하고 앞의 요소를 제외한 채 slice 를 반복해서 해결할 수도 있다. 이는 근데 이 때 배열을 조작하는 연산이 성능 상 작지 않을 거라는 생각이 들어서 하나의 식으로 만들었다.
  • 수학 식을 찾는게 쉽지 않다면 바로 배열 관련 함수를 이용해서 해결하는게 나을 듯
  • length - 1 * V가 핵심인데, 회전 했을 때 다음 값을 찾아낸다. length에서 -1을 한 이유는 한칸씩 이동해야하기 때문이다. -1이 없다면 이동하지 않고 본인의 값을 불러오게될 것이다. 만약 -2를 하면 두칸씩 회전하게 될 것이다.
/*
    [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 ]
profile
PS 연습장

0개의 댓글