Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function armies(input) {
- const armies = {};
- for (const line of input) {
- if (line.includes('arrives')) {
- const leader = line.split(' arrives').shift();
- if (!armies.hasOwnProperty(leader)) {
- armies[leader] = {};
- }
- } else if (line.includes(':')) {
- const [leader, armyInfo] = line.split(': ');
- if (armies.hasOwnProperty(leader)) {
- const [armyName, armyCount] = armyInfo.split(', ');
- armies[leader][armyName] = Number(armyCount);
- }
- } else if (line.includes('+')) {
- const [armyName, armyCount] = line.split(' + ');
- for (const leader in armies) {
- if (armies[leader].hasOwnProperty(armyName)) {
- armies[leader][armyName] += Number(armyCount);
- }
- }
- } else if (line.includes('defeat')) {
- const leader = line.split(' defeat').shift();
- if (armies.hasOwnProperty(leader)) {
- delete armies[leader];
- }
- }
- }
- const sorted = Object.entries(armies).sort(armiesSorter);
- for (const [leader, army] of sorted) {
- const totalArmy = Object.values(army).reduce((a, b) => a + b, 0);
- console.log(`${leader}: ${totalArmy}`);
- const sortedArmies = Object.entries(army).sort((a, b) => b[1] - a[1]);
- for (const army of sortedArmies) {
- console.log(`>>> ${army[0]} - ${army[1]}`);
- }
- }
- function armiesSorter(a, b) {
- const [armyNameA, armyCountA] = a;
- const [armyNameB, armyCountB] = b;
- const totalArmyA = (army) =>
- Object.values(armyCountA).reduce((a, b) => a + b, 0);
- const totalArmyB = (army) =>
- Object.values(armyCountB).reduce((a, b) => a + b, 0);
- const result = totalArmyB(armyCountB) - totalArmyA(armyCountA);
- return result;
- }
- }
Add Comment
Please, Sign In to add comment