Advertisement
vladovip

Moving Target _ Mid Exam Prep_JS Fund

Feb 24th, 2022 (edited)
1,333
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function movingTarget(inputArr) {
  2.   let targetList = inputArr.shift().split(" ").map(Number);
  3.   //console.log(targetList);
  4.   let commandsLine = inputArr;
  5.   // console.log(commandsLine);
  6.   let tokens = commandsLine.shift().split(" ");
  7.   // console.log(tokens);
  8.  
  9.   while (tokens != "End") {
  10.     let command = tokens[0];
  11.     let indexOfCommand = Number(tokens[1]);
  12.     let commandValue = Number(tokens[2]);
  13.     //  console.log(commandValue);
  14.  
  15.     if (command === "Shoot") {
  16.       for (let index in targetList) {
  17.         if (
  18.           index == indexOfCommand &&
  19.           targetList[indexOfCommand] > commandValue
  20.         ) {
  21.           targetList[indexOfCommand] -= commandValue;
  22.         }
  23.         if (
  24.           index == indexOfCommand &&
  25.           targetList[indexOfCommand] <= commandValue
  26.         ) {
  27.           targetList.splice(indexOfCommand, 1);
  28.         }
  29.       }
  30.     }
  31.  
  32.     if (command == "Add") {
  33.       for (let index = 0; index < targetList.length; index++) {
  34.         if (indexOfCommand >= 0 && indexOfCommand < targetList.length) {
  35.           targetList.splice(indexOfCommand, 0, commandValue);
  36.         }
  37.       }
  38.       if (indexOfCommand < 0 || indexOfCommand > targetList.length-1 ){
  39.         console.log(`Invalid placement!`);
  40.       }
  41.     }
  42.  
  43.     if (command == "Strike") {
  44.       for (let index in targetList) {
  45.         if (index == indexOfCommand) {
  46.           let startingIndex = indexOfCommand - commandValue;
  47.           let deleteCounter = commandValue * 2 + 1;
  48.           if (0 <= startingIndex && deleteCounter < targetList.length - 1) {
  49.             targetList.splice(startingIndex, deleteCounter);
  50.           } else if (startingIndex < 0 || deleteCounter > targetList.length - 1) {
  51.             console.log(`Strike missed!`);
  52.           }
  53.         }
  54.       }
  55.     }
  56.  
  57.     tokens = commandsLine.shift().split(" ");
  58.     if (command == "End") {
  59.       break;
  60.     }
  61.   }
  62.   console.log(targetList.join("|"));
  63. }
  64.  
  65. movingTarget([
  66.   "52 74 23 44 96 110",
  67.   "Shoot 5 10",
  68.   "Shoot 1 80",
  69.   "Strike 2 1",
  70.   "Add 22 3",
  71.   "End",
  72. ]);
  73.  
  74.  movingTarget(["1 2 3 4 5", "Strike 0 1", "End"]);
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement