Advertisement
gdimova

Feed the Animals

Apr 22nd, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.     let animals = {};
  3.     let areas = {}
  4.  
  5.     for (let parts of input) {
  6.         if (parts === 'Last Info') {
  7.             break;
  8.         }
  9.  
  10.         let [command, name, limit, area] = parts.split(':');
  11.         limit = Number(limit);
  12.  
  13.         if (command === 'Add') {
  14.             if (!animals.hasOwnProperty(name)) {
  15.                 animals[name] = limit;
  16.  
  17.                 if (!areas.hasOwnProperty(area)) {
  18.                     areas[area] = 1;
  19.                    
  20.                 } else {
  21.                     areas[area]++;
  22.                 }
  23.             }
  24.  
  25.             else {
  26.                 animals[name] += limit;
  27.             }
  28.         }
  29.  
  30.         else if (command === 'Feed') {
  31.             if (animals.hasOwnProperty(name)) {
  32.                 animals[name] -= limit;
  33.  
  34.                 if (animals[name] <= 0) {
  35.                     console.log(`${name} was successfully fed`);
  36.                     delete animals[name];
  37.                     areas[area]--
  38.                 }  
  39.  
  40.                 if (areas[area] <= 0){
  41.                     delete areas[area]
  42.                 }
  43.             }
  44.         }
  45.     }
  46.  
  47.     console.log(`Animals:`);
  48.     let sorted = Object.entries(animals)
  49.         .sort((a, b) => {
  50.             let result = b[1] - a[1]
  51.             if (result === 0) {
  52.                 result = a[0].localeCompare(b[0]);
  53.             }
  54.             return result
  55.  
  56.         })
  57.     for (let [name, limit] of sorted) {
  58.         console.log(`${name} -> ${limit}g`)
  59.     }
  60.  
  61.     console.log(`Areas with hungry animals:`);
  62.     let sortedAreas = Object.entries(areas)
  63.         .sort((a, b) => {
  64.             let result = b[1] - a[1]
  65.             return result
  66.         });
  67.  
  68.     for (let [name, count] of sortedAreas) {
  69.         console.log(`${name} : ${count}`);
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement