Guest User

Untitled

a guest
May 23rd, 2020
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input = []) {
  2.   let pirateShip = input.shift().split('>').map(Number);
  3.   let warShip = input.shift().split('>').map(Number);
  4.   let maxHealth = Number(input.shift());
  5.   let needRepair = 0;
  6.   let command;
  7.  
  8.   while ((command = input.shift()) !== 'Retire') {
  9.  
  10.     let currComand = command.split(' ');
  11.  
  12.     switch (currComand[0]) {
  13.       case 'Fire':
  14.         let index = +currComand[1];
  15.         let damage = +currComand[2];
  16.         if (index >= 0 && index < warShip.length) {
  17.           warShip[index] -= damage;
  18.           if (warShip[index] <= 0) {
  19.             console.log('You won! The enemy ship has sunken.');
  20.             return;
  21.           }
  22.         }
  23.         break;
  24.  
  25.       case 'Defend':
  26.         let startIndex = +currComand[1];
  27.         let endIndex = +currComand[2];
  28.         let attackPower = +currComand[3];
  29.  
  30.         if (startIndex >= 0 && startIndex < pirateShip.length && endIndex >= 0 && endIndex < pirateShip.length) {
  31.           for (let i = startIndex; i <= endIndex; i++) {
  32.             pirateShip[i] -= attackPower;
  33.  
  34.             if (pirateShip[i] <= 0) {
  35.               console.log(`You lost! The pirate ship has sunken.`);
  36.               return;
  37.             }
  38.           }
  39.         }
  40.         break;
  41.  
  42.       case 'Repair':
  43.         let repairIndex = +currComand[1];
  44.         let health = +currComand[2];
  45.         if (repairIndex >= 0 && repairIndex < pirateShip.length) {
  46.           pirateShip[repairIndex] += health;
  47.           if (pirateShip[repairIndex] > maxHealth) {
  48.             pirateShip[repairIndex] = maxHealth;
  49.           }
  50.         }
  51.         break;
  52.  
  53.       case 'Status':
  54.         for (let i = 0; i < pirateShip.length; i++) {
  55.           const element = pirateShip[i];
  56.           if (element < maxHealth * 0.20) {
  57.             needRepair++;
  58.           }
  59.         }
  60.         console.log(`${needRepair} sections need repair.`);
  61.     }
  62.   }
  63.   let sumWarShip = warShip.reduce((a, b) => a + b);
  64.   let sumPirate = pirateShip.reduce((acc, value) => acc + value);
  65.   console.log(`Pirate ship status: ${sumPirate}`);
  66.   console.log(`Warship status: ${sumWarShip}`);
  67. }
Advertisement
Add Comment
Please, Sign In to add comment