Sobes.tech
Middle

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. ```javascript function getRoute(tickets = []) { const cities = new Map(); for (const ticket of tickets) { cities.set(ticket.from, ticket); } const result = []; let currentCity = startcity; while (cities.has(currentCity)) { const next = cities.get(currentCity); result.push(next); currentCity = next.to; } return result; } console.clear() console.log(getRoute([ { from: 'London', to: 'Moscow' }, { from: 'NY', to: 'London' }, { from: 'Moscow', to: 'Spb' }, ])); ```

sobes.tech AI

Answer from AI

The provided code lacks the definition of the starting city startcity. To build a single route from a set of tickets, you need to:

  1. Find the city from which no one arrives — this will be the start.
  2. Create a Map for quick lookup of tickets by departure city.
  3. Iteratively go through the tickets, starting from the initial city, forming the route.

Example of a corrected and complete solution:

function getRoute(tickets = []) {
  const fromCities = new Set(tickets.map(t => t.from));
  const toCities = new Set(tickets.map(t => t.to));

  // Find the starting city — one that is in from but not in to
  let startcity = null;
  for (const city of fromCities) {
    if (!toCities.has(city)) {
      startcity = city;
      break;
    }
  }

  const citiesMap = new Map();
  for (const ticket of tickets) {
    citiesMap.set(ticket.from, ticket);
  }

  const result = [];
  let currentCity = startcity;

  while (citiesMap.has(currentCity)) {
    const nextTicket = citiesMap.get(currentCity);
    result.push(nextTicket);
    currentCity = nextTicket.to;
  }

  return result;
}

console.log(getRoute([
  { from: 'London', to: 'Moscow' },
  { from: 'NY', to: 'London' },
  { from: 'Moscow', to: 'Spb' },
]));

Output:

[
  { "from": "NY", "to": "London" },
  { "from": "London", "to": "Moscow" },
  { "from": "Moscow", "to": "Spb" }
]

Thus, the program reconstructs the route in the correct order.