dilyana2001

Untitled

Jun 15th, 2021 (edited)
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function pirates(input) {
  2.     let citiesMap = {}
  3.     while (input[0] !== 'Sail') {
  4.         let [cityName, population, gold] = input.shift().split('||')
  5.         population = Number(population)
  6.         gold = Number(gold)
  7.         if (!citiesMap.hasOwnProperty(cityName)) {
  8.             citiesMap[cityName] = { gold, population }
  9.         } else {
  10.             let cityInfo = citiesMap[cityName]
  11.             cityInfo.population += population
  12.             cityInfo.gold += gold
  13.         }
  14.     }
  15.     input.shift()
  16.     while (input[0] !== 'End') {
  17.         let [command, ...args] = input.shift().split('=>')
  18.         if (command === 'Plunder') {
  19.             let [town, people, gold] = args
  20.             people = Number(people)
  21.             gold = Number(gold)
  22.             let cityInfo = citiesMap[town]
  23.             cityInfo.population -= people
  24.             cityInfo.gold -= gold
  25.             console.log(`${town} plundered! ${gold} gold stolen, ${people} citizens killed.`)
  26.             if (cityInfo.population <= 0 || cityInfo.gold <= 0) {
  27.                 delete citiesMap[town]
  28.                 console.log(`${town} has been wiped off the map!`)
  29.             }
  30.         } else {
  31.             let [town, gold] = args
  32.             gold = Number(gold)
  33.             if (gold < 0) {
  34.                 console.log(`Gold added cannot be a negative number!`)
  35.             } else {
  36.                 let cityInfo = citiesMap[town]
  37.                 cityInfo.gold += gold
  38.                 console.log(`${gold} gold added to the city treasury. ${town} now has ${cityInfo.gold} gold.`)
  39.             }
  40.         }
  41.     }
  42.     let sortedCities = Object.entries(citiesMap).sort(sortCities)
  43.     if (sortedCities.length === 0) {
  44.         console.log(`Ahoy, Captain! All targets have been plundered and destroyed!`)
  45.     } else {
  46.         console.log(`Ahoy, Captain! There are ${sortedCities.length} wealthy settlements to go to:`)
  47.         for (let [cityName, cityInfo] of sortedCities) {
  48.             let { gold, population } = cityInfo
  49.             console.log(`${cityName} -> Population: ${population} citizens, Gold: ${gold} kg`)
  50.         }
  51.     }
  52.  
  53.     function sortCities(a, b) {
  54.         let [aCityName, aCityInfo] = a
  55.         let [bCityName, bCityInfo] = b
  56.         let result = bCityInfo.gold - aCityInfo.gold
  57.         if (result === 0) {
  58.             return aCityName.localeCompare(bCityName)
  59.         }
  60.         return result
  61.     }
  62. }
Add Comment
Please, Sign In to add comment