nikolayneykov

Untitled

Mar 7th, 2019
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.     let houses = input[1].split(' ').filter(x => x !== '').map(Number);
  3.     let commands = input.slice(2);
  4.     let position = 0;
  5.  
  6.     for (let command of commands) {
  7.         let tokens = command.split(' ').filter(x => x !== '');
  8.         let currentCommand = tokens[0];
  9.         if (currentCommand === 'Forward') {
  10.             let numberOfSteps = +tokens[1];
  11.             if (position + numberOfSteps < houses.length) {
  12.                 position += numberOfSteps;
  13.                 houses.splice(position, 1);
  14.             }
  15.         } else if (currentCommand === 'Back') {
  16.             let numberOfSteps = +tokens[1];
  17.  
  18.             if (position - numberOfSteps >= 0) {
  19.                 position-=numberOfSteps;
  20.                 houses.splice(position, 1);
  21.             }
  22.         } else if (currentCommand === 'Gift') {
  23.             let index = +tokens[1];
  24.             if (index >= 0 && index <= houses.length) {
  25.                 let houseNumber = +tokens[2];
  26.                 position = index;
  27.                 houses.splice(position, 0, houseNumber);
  28.             }
  29.         } else if (currentCommand === 'Swap') {
  30.             let firstIndex = houses.indexOf(+tokens[1]);
  31.             let secondIndex = houses.indexOf(+tokens[2]);
  32.  
  33.             if (firstIndex !== -1 && secondIndex !== -1) {
  34.                 let temp = houses[firstIndex];
  35.                 houses[firstIndex] = houses[secondIndex];
  36.                 houses[secondIndex] = temp;
  37.             }
  38.         }
  39.     }
  40.  
  41.     console.log(`Position: ${position}\n${houses.join(', ')}`);
  42. }
Add Comment
Please, Sign In to add comment