2021. 2. 27. 20:22ㆍ알고리즘/코딜리티
Task description
An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place.
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]
(elements are shifted right by one index and 6 is moved to the first place).
The goal is to rotate array A K times;
that is, each element of A will be shifted to the right K times.
Write a function:
function solution(A, K);
that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
For example, given
A = [3, 8, 9, 7, 6] K = 3
the function should return [9, 7, 6, 3, 8].
Three rotations were made:
[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
For another example, given
A = [0, 0, 0] K = 1
the function should return [0, 0, 0]
Given
A = [1, 2, 3, 4] K = 4
the function should return [1, 2, 3, 4]
Assume that:
- N and K are integers within the range [0..100];
- each element of array A is an integer within the range [−1,000..1,000].
In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.
Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
🌈 CyclicRotation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/**
* Rotate an array to the right by a given number of steps.
* @param {*} A : 순환할 배열
* @param {*} K : 순환 횟수
*/
function solution(A, K) {
let arr = A.length == 0 ? [] : A; // empty array check
for(let i = 0; i < K; i++) {
let last = arr.pop(); // 배열의 마지막 요소 제거
arr.unshift(last); // 배열의 처음에 요소 추가
}
return A;
}
|
cs |
📢 첫 시도엔 87%로 실패했다.
코딜리티의 가장 좋은 점 중 하나는, 테스트 케이스를 공개하며 틀린 이유를 알려준다!
나 같은 경우에는 empty array에 대한 유효성 검증이 빠져있었다.
let arr = A.length == 0 ? [] : A; // empty array check
매개변수로 받은 A 배열 크기가 0이면 빈 배열 선언해주기!
👩💻 풀어보기 👨💻 https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/start/
'알고리즘 > 코딜리티' 카테고리의 다른 글
[Codility] [Javascript] MissingInteger (0) | 2021.03.02 |
---|---|
[Codility] [Javascript] PermMissingElem (0) | 2021.03.01 |
[Codility] [Javascript] FrogJmp (0) | 2021.02.28 |
[Codility] [Javascript] OddOccurrencesInArray (1) | 2021.02.27 |
[Codility] [Javascript] BinaryGap (0) | 2021.02.27 |