nikolayneykov

Untitled

Mar 6th, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arr) {
  2.     let numberOfCommands = +arr.shift()
  3.     let theListOfHouses = arr[0].split(" ").map(Number);
  4.     arr.shift()
  5.     let santaPosition = 0;
  6.     for (let i = 0; i < arr.length; i++) {
  7.         // if (numberOfCommands <= 0) {
  8.         //     break;
  9.         // }
  10.         let currentLine = arr[i].split(" ");
  11.         let command = currentLine[0]
  12.         let value = +currentLine[1]
  13.         let swapOrGiftValue = +currentLine[2];
  14.  
  15.         if (command === "Forward" && (santaPosition + value) < theListOfHouses.length) {
  16.  
  17.             santaPosition = santaPosition + value;
  18.             theListOfHouses.splice(santaPosition, 1)
  19.  
  20.         }
  21.         else if (command === "Back" && !(santaPosition - value < 0)) {
  22.             santaPosition = santaPosition - value;
  23.             theListOfHouses.splice(santaPosition, 1)
  24.         }
  25.         else if (command === "Swap") {
  26.             let index1 = theListOfHouses.indexOf(value);
  27.             let index2 = theListOfHouses.indexOf(swapOrGiftValue);
  28.  
  29.             if (index1 !== -1 && index2 !== -1) {
  30.                 let temp = theListOfHouses[index1];
  31.                 theListOfHouses[index1] = theListOfHouses[index2];
  32.                 theListOfHouses[index2] = temp;
  33.             }
  34.         }
  35.         else if (command === "Gift") {
  36.             if (value >= 0 && value < arr.length) {
  37.                 theListOfHouses.splice(value, 0, swapOrGiftValue)
  38.                 santaPosition = value
  39.             }
  40.         }
  41.         numberOfCommands--;
  42.  
  43.     }
  44.     console.log(`Position: ${santaPosition}\n${theListOfHouses.join(", ")}`)
  45. }
Advertisement
Add Comment
Please, Sign In to add comment