simeonshopov

Armies

Apr 15th, 2021
477
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arr) {
  2.   let leaders = [];
  3.  
  4.   for (let info of arr) {
  5.     if (info.includes('arrives')) {
  6.       const leader = info.substring(0, info.indexOf('arrive') - 1);
  7.       leaders.push([leader, new Map()]);
  8.     } else if (info.includes('defeated')) {
  9.       const leader = info.substring(0, info.indexOf('defeated') - 1);
  10.       if (leaders.filter(x => x[0] === leader).length > 0) { leaders.splice(leaders.indexOf(leaders.filter(x => x[0] === leader)[0]), 1); }
  11.     } else if (info.includes(': ')) {
  12.       const leader = info.substring(0, info.indexOf(':'));
  13.       const army = info.substring(info.indexOf(':') + 2, info.indexOf(','));
  14.       let armyCount = Number(info.substring(info.lastIndexOf(' ')),);
  15.       if (leaders.filter(x => x[0] == leader).length > 0) { leaders.filter(x => x[0] == leader)[0][1].set(army, armyCount); }
  16.     } else if (info.includes('+')) {
  17.       const army = info.substring(0, info.indexOf(' +') );
  18.       const newCount = Number(info.substring(info.indexOf('+') + 1,));
  19.       if (leaders.filter(x => x[1].has(army)).length > 0) {
  20.         let armyToChange = leaders.filter(x => x[1].has(army))[0][1];
  21.         armyToChange.set(army, armyToChange.get(army) + newCount);
  22.       }
  23.     }
  24.   }
  25.  
  26.   for (let leader of leaders.sort((a, b) => [...b[1].values()].reduce((a, b) => a + b) - [...a[1].values()].reduce((a, b) => a + b))) {
  27.     console.log(`${leader[0]}: ${[...leader[1].values()].reduce((a, b) => a + b)}`);
  28.     [...leader[1].entries()].sort((a, b) => b[1] - a[1]).forEach(x => console.log(`>>> ${x[0]} - ${x[1]}`));
  29.   }
  30. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×