Advertisement
fbinnzhivko

Untitled

Dec 17th, 2016
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(flights) {
  2.     const LAND = 'land';
  3.  
  4.     let landed = [];
  5.     let townsStats = new Map();
  6.  
  7.     for (let flight of flights) {
  8.         let [id, town, passengers, action] = flight.split(/\s+/g);
  9.  
  10.         if (action === LAND) {
  11.             if (landed.indexOf(id) >= 0)
  12.                 continue;
  13.  
  14.             landed.push(id);
  15.         } else {
  16.             if (landed.indexOf(id) < 0)
  17.                 continue;
  18.  
  19.             landed = landed.filter(p => p != id);
  20.         }
  21.  
  22.         if (!townsStats.has(town)) {
  23.             townsStats.set(town, {arrivals: 0, departures: 0, planes: new Set()});
  24.         }
  25.  
  26.         if (action === LAND)
  27.             townsStats.get(town).arrivals += Number(passengers);
  28.         else
  29.             townsStats.get(town).departures += Number(passengers);
  30.  
  31.         townsStats.get(town).planes.add(id);
  32.     }
  33.    
  34.     console.log('Planes left:');
  35.     console.log(landed
  36.         .sort((p1, p2) => p1.localeCompare(p2))
  37.         .map(p => `- ${p}`)
  38.         .join('\n'));
  39.  
  40.     let sortedTowns = [...townsStats.keys()]
  41.         .sort(function (t1, t2) {
  42.             let res = townsStats.get(t2).arrivals - townsStats.get(t1).arrivals;
  43.             if (res === 0) {
  44.                 res = t1.localeCompare(t2);
  45.             }
  46.  
  47.             return res;
  48.         });
  49.  
  50.     for (let town of sortedTowns) {
  51.         let currentTown = townsStats.get(town);
  52.  
  53.         console.log(town);
  54.         console.log(`Arrivals: ${currentTown.arrivals}`);
  55.         console.log(`Departures: ${currentTown.departures}`);
  56.         console.log('Planes:');
  57.         console.log([...currentTown.planes.values()]
  58.             .sort((p1, p2) => p1.localeCompare(p2))
  59.             .map(p => `-- ${p}`)
  60.             .join('\n'));
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement