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:
(요약) 첫 번째 요소가 출발, 두 번째 요소가 도착인 배열 요소들을 연결해서 최초 출발점부터 최종 도착점까지 나열해라.
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
.