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. You need to write a program that returns these same ticket objects in the order of the route. */ function getRoute(tickets = [], startCity) { // your code here } console.clear() console.log(getRoute([ { from: 'London', to: 'Moscow' }, { from: 'NY', to: 'London' }, { from: 'Moscow', to: 'SPb' }, ], 'NY')); /* [ { from: 'NY', to: 'London' }, { from: 'London', to: 'Moscow' }, { from: 'Moscow', to: 'SPb' }, ] */
sobes.tech AI
Answer from AI
To reconstruct a route from a set of tickets, you can build a dictionary (Map) from the departure city to the ticket, and then sequentially go from the starting city, choosing the next ticket by the key.
Example solution in JavaScript:
function getRoute(tickets = [], startCity) {
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;
}
console.log(getRoute([
{ from: 'London', to: 'Moscow' },
{ from: 'NY', to: 'London' },
{ from: 'Moscow', to: 'SPb' },
], 'NY'));
This code creates a map for quick lookup of tickets by departure city and then constructs the route starting from startCity until it reaches the final destination.