Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve(input) {
- let houses = input[1].split(' ').filter(x => x !== '').map(Number);
- let commands = input.slice(2);
- let position = 0;
- for (let command of commands) {
- let tokens = command.split(' ').filter(x => x !== '');
- let currentCommand = tokens[0];
- if (currentCommand === 'Forward') {
- let numberOfSteps = +tokens[1];
- if (position + numberOfSteps < houses.length) {
- position += numberOfSteps;
- houses.splice(position, 1);
- }
- } else if (currentCommand === 'Back') {
- let numberOfSteps = +tokens[1];
- if (position - numberOfSteps >= 0) {
- position-=numberOfSteps;
- houses.splice(position, 1);
- }
- } else if (currentCommand === 'Gift') {
- let index = +tokens[1];
- if (index >= 0 && index <= houses.length) {
- let houseNumber = +tokens[2];
- position = index;
- houses.splice(position, 0, houseNumber);
- }
- } else if (currentCommand === 'Swap') {
- let firstIndex = houses.indexOf(+tokens[1]);
- let secondIndex = houses.indexOf(+tokens[2]);
- if (firstIndex !== -1 && secondIndex !== -1) {
- let temp = houses[firstIndex];
- houses[firstIndex] = houses[secondIndex];
- houses[secondIndex] = temp;
- }
- }
- }
- console.log(`Position: ${position}\n${houses.join(', ')}`);
- }
Add Comment
Please, Sign In to add comment