CodeWars 코딩 문제 2021/03/13 - Follow that Spy

이호현·2021년 3월 13일
0

Algorithm

목록 보기
88/138

[문제]

We are tracking down our rogue agent Matthew Knight also known as Roy Miller. He travels from places to places to avoid being tracked. Each of his travels are based on a list of itineraries in an unusual or incorrect order. The task is to determine the routes he will take in his every journey.

Task
You are given an array of routes of his itineraries. List down the only places where he will go in correct order based on his itineraries.

Example

Given the following routes:

[ [USA, BRA], [JPN, PHL], [BRA, UAE], [UAE, JPN] ]

The result will be:

"USA, BRA, UAE, JPN, PHL"

Note:

  • It is safe to assume that there will be no repeating place with a different route.
  • There are no empty routes.
  • There will be at least one (1) route (from one waypoint to another).

(요약) 첫 번째 요소가 출발, 두 번째 요소가 도착인 배열 요소들을 연결해서 최초 출발점부터 최종 도착점까지 나열해라.

[풀이]

function findRoutes(routes) {
  let answer = '';
  let next = '';
  const routesArr = routes.reduce((returnArr, arr) => {
    returnArr[0].push(arr[0]);
    returnArr[1].push(arr[1]);
    return returnArr;
  }, [[], []]);

  const start = routesArr[0].filter(str => !routesArr[1].includes(str))[0];
  answer += start;
  next = start;

  for(let i = 0; i < routesArr[0].length; i++) {
    const index = routesArr[0].indexOf(next);
    next = routesArr[1][index];
    answer += `, ${next}`;
  }

  return answer;
}

routes배열을 reduce로 출발점과 도착점끼리 분리해서 정리한다.

그리고 출발점에서 filter로 도착점에 없는 요소를 최초 시작점으로 설정하고, 경로에 추가.

반복문을 이용해 출발점의 index를 찾고 그 index에 위치한 도착점을 경로에 추가하고 다음 시작점으로 설정.

출발점만 모아놓은 배열의 횟수만큼만 반복시키고, 얻어진 경로를 return.

profile
평생 개발자로 살고싶습니다

0개의 댓글