Problem Solution/Programmers

[프로그래머스/JS] 배열 회전시키기

yuri lee 2023. 10. 20. 18:09
반응형

Problem Description

정수가 담긴 배열 numbers와 문자열 direction가 매개변수로 주어집니다. 배열 numbers의 원소를 direction 방향으로 한 칸씩 회전시킨 배열을 return하도록 solution 함수를 완성해주세요.

 

Restrictions.

  • 3 ≤ numbers의 길이 ≤ 20
  • direction은 "left" 와 "right" 둘 중 하나입니다.

 

Input/Output Example

  • 입출력 예 #1 numbers 가 [1, 2, 3]이고 direction이 "right" 이므로 오른쪽으로 한 칸씩 회전시킨 [3, 1, 2]를 return합니다.
  • 입출력 예 #2  numbers 가 [4, 455, 6, 4, -1, 45, 6]이고 direction이 "left" 이므로 왼쪽으로 한 칸씩 회전시킨 [455, 6, 4, -1, 45, 6, 4]를 return합니다.

 

My solution

function solution(numbers, direction) {
  if (direction === "left") {
    const firstElement = numbers.shift(); 
    numbers.push(firstElement); 
  } else if (direction === "right") {
    const lastElement = numbers.pop(); 
    numbers.unshift(lastElement); 
  }

  return numbers;
}
  • push() : 배열의 맨 끝에 값 추가
  • unshift() : 배열의 맨 앞에 값 추가
  • pop() : 배열의 맨 끝에 값 제거
  • shift(): 배열의 맨 앞에 값 제거

 

Another solutions

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

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

    answer = numbers;

    return answer;
}

 


https://school.programmers.co.kr/learn/courses/30/lessons/120844

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

 

Array.prototype.shift() - JavaScript | MDN

shift() 메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다. 이 메서드는 배열의 길이를 변하게 합니다.

developer.mozilla.org

 

반응형