Advertisement
Neri0817

02. Treasure Hunt

Feb 19th, 2022
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function treasureHunt(array) {
  2.   let chest = array.shift().split("|");
  3.   let commands = array.slice();
  4.   let stolen = [];
  5.  
  6.   for (let i = 0; i < array.length; i++) {
  7.     let current = commands.shift();
  8.  
  9.     if (current === "Yohoho!") {
  10.       break;
  11.     }
  12.  
  13.     let curr = current.split(" ");
  14.     let comm = curr.shift();
  15.  
  16.     if (comm === "Loot") {
  17.       for (let i = 0; i < curr.length; i++) {
  18.         let item = curr[i];
  19.         if (!chest.includes(item)) {
  20.           chest.unshift(item);
  21.         }
  22.       }
  23.     } else if (comm === "Drop") {
  24.       let index = curr.shift();
  25.       let item = chest.splice(+index, 1);
  26.       chest.push(item);
  27.     } else if (comm === "Steal") {
  28.       let count = Number(curr.shift());
  29.       stolen = chest.slice(-count);
  30.     }
  31.   }
  32.  
  33.   console.log(stolen.join(", "));
  34.  
  35.   if (chest.length != stolen.length) {
  36.     let sum = 0;
  37.     let counter = 0;
  38.     for (let i = 0; i < chest.length - stolen.length; i++) {
  39.       sum += chest[i].length;
  40.       counter++;
  41.     }
  42.     let averageGain = sum / counter;
  43.  
  44.     console.log(
  45.       `Average treasure gain: ${averageGain.toFixed(2)} pirate credits.`
  46.     );
  47.   } else {
  48.     console.log("Failed treasure hunt.");
  49.   }
  50. }
  51. treasureHunt([
  52.   "Gold|Silver|Bronze|Medallion|Cup",
  53.   "Loot Wood Gold Coins",
  54.   "Loot Silver Pistol",
  55.   "Drop 3",
  56.   "Steal 3",
  57.   "Yohoho!",
  58. ]);
  59.  
  60. treasureHunt([
  61.   "Diamonds|Silver|Shotgun|Gold",
  62.   "Loot Silver Medals Coal",
  63.   "Drop -1",
  64.   "Drop 1",
  65.   "Steal 6",
  66.   "Yohoho!",
  67. ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement