[프로그래머스 | Javascript] 코딩테스트 입문 - 배열 회전시키기

박기영·2022년 11월 1일
0

프로그래머스

목록 보기
69/159

solution

function solution(numbers, direction) {
    if(direction === "right"){
        let splicedArr = numbers.splice(0, numbers.length - 1);
        
        return [...numbers ,...splicedArr];
    }
    
    if(direction === "left"){
        let splicedArr = numbers.splice(1, numbers.length - 1);
        
        return [...splicedArr, ...numbers];
    }
}

간단하다.
right가 나오면 오른쪽으로 한 칸씩 가야하므로, 맨 끝에 있는 원소만 앞으로 옮기고
left가 나오면 왼쪽으로 한 칸씩 가야하므로, 맨 앞에 있는 원소만 뒤로 옮기면 된다.
상당히 불편해보이는 방법이다.

같은 방법을 구현하는데 pop(), shift()를 활용할 수 있을 것 같다.

다른 분 풀이

function solution(numbers, direction) {
    let answer = [];

    if ("right" == direction) {
        numbers.unshift(numbers.pop());
    } else {
        numbers.push(numbers.shift());
    }

    answer = numbers;

    return answer;
}

필자가 꼬아서 생각한 것을 간단하게 해결하셨다.
pop(), shift()를 사용하여 간단하게 구현하셨다.

profile
나를 믿는 사람들을, 실망시키지 않도록

0개의 댓글