nikolayneykov

Untitled

Mar 6th, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.     let numCommands = +input[0];
  3.     let housesArray = input[1].split(' ');
  4.     let position = 0;
  5.  
  6.     for (let i = 2; i < input.length; i++) {
  7.  
  8.         let elements = input[i].split(' ');
  9.  
  10.         let command = elements[0];
  11.         let number = +elements[1];
  12.  
  13.         if (command === 'Forward' || command === 'Back') {
  14.             if (command == 'Back') { //ако имаме Back трябва да се движим назад по масива
  15.                 number = -number;  
  16.             }
  17.  
  18.             if (position + number >= 0 && position + number < housesArray.length) { //проверяваме дали ще бъдем в рамките на масива
  19.                 position += number;
  20.                 housesArray.splice(position, 1);
  21.             }
  22.  
  23.         }
  24.         if (command === 'Gift') {
  25.             let index = elements[1];
  26.             if (index >= 0 && index < housesArray.length) { //проверяваме дали индекса е в рамките на масива
  27.                 let houseNumber = elements[2];
  28.                 housesArray.splice(index, 0, houseNumber);
  29.                 position=index; //сменяме позицията ни с новия индекс
  30.             }
  31.  
  32.         }
  33.         if (command === 'Swap') {
  34.             let firstIndex = elements[1];
  35.             let secondIndex = elements[2];
  36.             if (housesArray.includes(firstIndex) && housesArray.includes(secondIndex)) {
  37.                 let index1 = housesArray.indexOf(firstIndex);
  38.                 let index2 = housesArray.indexOf(secondIndex);
  39.                 //разменяме отдолу стойностите
  40.                 let temp = housesArray[index1];
  41.                 housesArray[index1] = housesArray[index2];
  42.                 housesArray[index2] = temp;
  43.             }
  44.         }
  45.  
  46.     }
  47.     console.log("Position: " + position);
  48.     console.log(housesArray.join(", "));
  49.  
  50. }
Advertisement
Add Comment
Please, Sign In to add comment