프로그래밍/알고리즘, 프로그래밍 언어

[코딩테스트] rowBikesOut (JavaScript)

제이콥J 2022. 2. 3. 11:23

문제

설명

There is a cycling road with bikes lined up in a row. If an owner wants to take out the bike located in N, next bikes should be taken out. Then, bikes must enter the end of the road in the order in which they exited. Complete a function that returns an array of bikes after they going out and in.

매개변수

  • rowBikes : Array type with bikes in a regular sequence
  • n : number type

아웃풋

Array should be returned.

범위

  • 3 <= rowsBikes.length <= 100
  • 1 <= n <= 100

 

Solution

n을 기준으로 0번 인덱스 요소에서 n까지 요소를 배열에 담기

마지막 인덱스 요소에서 n까지 요소를 배열에 담기

indexOf 메소드로 n의 인덱스를 찾고, reverse 메소드를 함께 사용하기

 

function rowBikesOut(rowBikes, n) {
  let result = [];
  const idx = rowBikes.indexOf(n);

  let head = rowBikes.slice(0,idx);
  let tail = rowBikes.slice(idx+1, rowBikes.length);

  result.push(...head)
  result.push(...tail.reverse());

  return result;
}
반응형