didkoslawow

Untitled

Mar 4th, 2023
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function armies(input) {
  2.   const armies = {};
  3.  
  4.   for (const line of input) {
  5.     if (line.includes('arrives')) {
  6.       const leader = line.split(' arrives').shift();
  7.  
  8.       if (!armies.hasOwnProperty(leader)) {
  9.         armies[leader] = {};
  10.       }
  11.     } else if (line.includes(':')) {
  12.       const [leader, armyInfo] = line.split(': ');
  13.  
  14.       if (armies.hasOwnProperty(leader)) {
  15.         const [armyName, armyCount] = armyInfo.split(', ');
  16.         armies[leader][armyName] = Number(armyCount);
  17.       }
  18.     } else if (line.includes('+')) {
  19.       const [armyName, armyCount] = line.split(' + ');
  20.  
  21.       for (const leader in armies) {
  22.         if (armies[leader].hasOwnProperty(armyName)) {
  23.           armies[leader][armyName] += Number(armyCount);
  24.         }
  25.       }
  26.     } else if (line.includes('defeat')) {
  27.       const leader = line.split(' defeat').shift();
  28.  
  29.       if (armies.hasOwnProperty(leader)) {
  30.         delete armies[leader];
  31.       }
  32.     }
  33.   }
  34.  
  35.   const sorted = Object.entries(armies).sort(armiesSorter);
  36.  
  37.   for (const [leader, army] of sorted) {
  38.     const totalArmy = Object.values(army).reduce((a, b) => a + b, 0);
  39.  
  40.     console.log(`${leader}: ${totalArmy}`);
  41.  
  42.     const sortedArmies = Object.entries(army).sort((a, b) => b[1] - a[1]);
  43.  
  44.     for (const army of sortedArmies) {
  45.       console.log(`>>> ${army[0]} - ${army[1]}`);
  46.     }
  47.   }
  48.  
  49.   function armiesSorter(a, b) {
  50.     const [armyNameA, armyCountA] = a;
  51.     const [armyNameB, armyCountB] = b;
  52.  
  53.     const totalArmyA = (army) =>
  54.       Object.values(armyCountA).reduce((a, b) => a + b, 0);
  55.     const totalArmyB = (army) =>
  56.       Object.values(armyCountB).reduce((a, b) => a + b, 0);
  57.  
  58.     const result = totalArmyB(armyCountB) - totalArmyA(armyCountA);
  59.  
  60.     return result;
  61.   }
  62. }
Add Comment
Please, Sign In to add comment