kstoyanov

03. P!rates js exam

Aug 12th, 2020 (edited)
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(args) {
  2.   let sailInputLine = args.shift();
  3.  
  4.   const cities = {};
  5.  
  6.   while (sailInputLine !== 'Sail') {
  7.     let [cityName, population, gold] = sailInputLine.split('||');
  8.     population = Number(population);
  9.     gold = Number(gold);
  10.     if (!Object.prototype.hasOwnProperty.call(cities, cityName)) {
  11.       cities[cityName] = { population, gold };
  12.     } else {
  13.       cities[cityName].population += population;
  14.       cities[cityName].gold += gold;
  15.     }
  16.  
  17.     sailInputLine = args.shift();
  18.   }
  19.  
  20.   let eventInputLine = args.shift();
  21.  
  22.   while (eventInputLine !== 'End') {
  23.     let [event, town, arg1, arg2] = eventInputLine.split('=>');
  24.     arg1 = Number(arg1);
  25.     arg2 = Number(arg2);
  26.  
  27.     switch (event) {
  28.       case 'Plunder':
  29.         console.log(`${town} plundered! ${arg2} gold stolen, ${arg1} citizens killed.`);
  30.         cities[town].population -= arg1;
  31.         cities[town].gold -= arg2;
  32.  
  33.         if (cities[town].population === 0 || cities[town].gold === 0) {
  34.           delete cities[town];
  35.           console.log(`${town} has been wiped off the map!`);
  36.         }
  37.  
  38.  
  39.         break;
  40.  
  41.       case 'Prosper':
  42.  
  43.         if (arg1 > 0) {
  44.           cities[town].gold += arg1;
  45.           console.log(`${arg1} gold added to the city treasury. ${town} now has ${cities[town].gold} gold.`);
  46.         } else {
  47.           console.log('Gold added cannot be a negative number!');
  48.         }
  49.  
  50.         break;
  51.  
  52.       default:
  53.         break;
  54.     }
  55.     eventInputLine = args.shift();
  56.   }
  57.  
  58.   if (Object.keys(cities).length !== 0) {
  59.     console.log(`Ahoy, Captain! There are ${Object.keys(cities).length} wealthy settlements to go to:`);
  60.  
  61.     Object.entries(cities)
  62.       .sort((a, b) => b[1].gold - a[1].gold || a[0].localeCompare(b[0]))
  63.       .forEach((city) => {
  64.         const [name, props] = city;
  65.         const { population, gold } = props;
  66.  
  67.         console.log(`${name} -> Population: ${population} citizens, Gold: ${gold} kg`);
  68.       });
  69.   } else {
  70.     console.log('Ahoy, Captain! All targets have been plundered and destroyed!');
  71.   }
  72. }
Add Comment
Please, Sign In to add comment