Middle
/* We have a set of tickets of the following form: [ { from: 'London', to: 'Moscow' }, { from: 'NY', to: 'London' }, { from: 'Moscow', to: 'Spb' }, ... ] From these tickets, a single continuous route can be constructed. There are no loops or repetitions in the route. Write a program that returns these ticket objects in the order of the route. */ function getRoute(tickets = [], startCity = 'NY') { // your code here }
sobes.tech AI
Answer from AI
To solve the task, you need to order the tickets so that each subsequent ticket starts where the previous one ended. Since the route is unique and continuous, you can build a dictionary (Map) from the departure city to the ticket, and then, starting from the initial city, sequentially take the next ticket.
Example solution in JavaScript:
function getRoute(tickets = [], startCity = 'NY') {
const map = new Map();
tickets.forEach(ticket => {
map.set(ticket.from, ticket);
});
const route = [];
let currentCity = startCity;
while (map.has(currentCity)) {
const ticket = map.get(currentCity);
route.push(ticket);
currentCity = ticket.to;
}
return route;
}
// Example usage:
const tickets = [
{ from: 'London', to: 'Moscow' },
{ from: 'NY', to: 'London' },
{ from: 'Moscow', to: 'Spb' },
];
console.log(getRoute(tickets, 'NY'));
// Will output tickets in order: NY->London, London->Moscow, Moscow->Spb