Advertisement
PowerCell46

Treasure hunt JS

Dec 9th, 2022
1,046
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function treasureHunt(array) {
  2.     let initialLootArray = (array[0]).split("|");
  3.     let index = 1;
  4.     let currentCommand = array[index];
  5.     let stealArray = [];
  6.  
  7.     while (currentCommand !== "Yohoho!") {
  8.         let currentInput = currentCommand.split(" ");
  9.  
  10.         switch (currentInput[0]) {
  11.             case "Loot":
  12.                 let lootIndex = 1;
  13.                 while (lootIndex < Number(currentInput.length)) {
  14.                     let currentItem = currentInput[lootIndex];
  15.                     if (!initialLootArray.includes(currentItem)) {
  16.                         initialLootArray.unshift(currentItem);
  17.                     }
  18.                     lootIndex++;
  19.                 } break;
  20.  
  21.             case "Drop":
  22.                 let dropIndex = Number(currentInput[1]);
  23.                 if (dropIndex >= 0 && dropIndex < Number(initialLootArray.length)) {
  24.                     let removedItem = initialLootArray.splice(dropIndex, 1);
  25.                     initialLootArray.push(removedItem[0]);
  26.                 } break;
  27.  
  28.             case "Steal":
  29.                 let numberOfStolenItems = Number(currentInput[1]);
  30.                 let stolenItems = initialLootArray.splice(-numberOfStolenItems);
  31.                 console.log(stolenItems.join(", "));
  32.                 break;
  33.         }
  34.  
  35.         index++;
  36.         currentCommand = array[index];
  37.     }
  38.  
  39.     let averageTreasureGain = 0;
  40.     for (let finalIndex = 0; finalIndex < Number(initialLootArray.length); finalIndex++) {
  41.         let currentItemLength = Number((initialLootArray[finalIndex]).length);
  42.         averageTreasureGain += currentItemLength;
  43.     }
  44.  
  45.     if (averageTreasureGain > 0) {
  46.         averageTreasureGain = averageTreasureGain / Number(initialLootArray.length);
  47.         console.log(`Average treasure gain: ${averageTreasureGain.toFixed(2)} pirate credits.`);
  48.     } else if (averageTreasureGain === 0) {
  49.         console.log(`Failed treasure hunt.`);
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement