Advertisement
Spocoman

02. Santa's Gifts

Feb 11th, 2024
1,096
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function santasGifts(input) {
  2.     let commandNumbers = Number(input[0]);
  3.  
  4.     let houses = input[1].split(' ');
  5.  
  6.     let index = 0;
  7.  
  8.     for (let i = 2; i < commandNumbers + 2; i++) {          
  9.         let currentIndex = index;
  10.  
  11.         let command = input[i].split(' ');
  12.  
  13.         if (command[0] == "Forward" || command[0] == "Back") {
  14.             let steps = Number(command[1]);
  15.             currentIndex += (command[0] == "Forward" ? steps : -steps);
  16.             if (currentIndex >= 0 && currentIndex < houses.length) {
  17.                 index = currentIndex;
  18.                 houses.splice(index, 1);
  19.             }
  20.         } else if (command[0] == "Gift") {
  21.             currentIndex = Number(command[1]);
  22.             if (currentIndex >= 0 && currentIndex < houses.length) {
  23.                 index = currentIndex;
  24.                 houses.splice(index, 0, command[2]);
  25.             }
  26.         } else if (command[0] == "Swap") {
  27.             let index1 = houses.indexOf(command[1]),
  28.                 index2 = houses.indexOf(command[2]);
  29.  
  30.             if (index1 != -1 && index2 != -1) {
  31.                 let value = houses[index1];
  32.                 houses[index1] = houses[index2];
  33.                 houses[index2] = value;
  34.             }    
  35.         }
  36.     }
  37.  
  38.     console.log(`Position: ${index}`);
  39.  
  40.     if (houses.length > 0) {
  41.         console.log(houses.join(", "));
  42.     }
  43.     return;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement