Skip to content

Instantly share code, notes, and snippets.

@trinhvanhuy
Last active May 11, 2018 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trinhvanhuy/ed0c8d59f34e45593e3cfc8d3a524495 to your computer and use it in GitHub Desktop.
Save trinhvanhuy/ed0c8d59f34e45593e3cfc8d3a524495 to your computer and use it in GitHub Desktop.
testcontentsquare
const lib = {
'L': {
'N': 'W',
'E': 'N',
'S': 'E',
'W': 'S',
},
'R': {
'N': 'E',
'E': 'S',
'S': 'W',
'W': 'N',
},
}
const calculateInput = () => {
let mapInit = {}
const lineReader = require('readline').createInterface({
input: require('fs').createReadStream('test.txt')
});
const arrayInput = [];
let currentValue = {};
let numLine = 0;
lineReader.on('line', function(line) {
if (line.trim().length > 0) {
if (numLine === 0) {
mapInit = (line.split(' ')).map( x=> parseInt(x, 10));
} else if (numLine % 2 === 1) {
let values = (line.split(' ')) ;
currentValue = {
'x': parseInt(values[0], 10),
'y': parseInt(values[1], 10),
'direction': values[2],
};
} else if (numLine % 2 === 0) {
arrayInput.push({
'initPost' : currentValue,
'moves': line.trim()
});
}
numLine++;
}
}).on('close', function() {
const map = { x: mapInit[0], y: mapInit[1] };
const result = [];
for (let i = 0; i < arrayInput.length; i++) {
const pos = arrayInput[i].initPost;
const moves = arrayInput[i].moves;
let currentDirection = pos.direction;
for (let j = 0; j < moves.length; j++) {
if (moves.charAt(j) === 'L' || moves.charAt(j) === 'R') {
currentDirection = lib[moves.charAt(j)][currentDirection];
} else if (moves.charAt(j) === 'F') {
let x = pos.x;
let y = pos.y;
if (currentDirection === 'N') {
y = y + 1;
} else if (currentDirection === 'E') {
x = x + 1;
} else if (currentDirection === 'S') {
y = y - 1;
} else if (currentDirection === 'W') {
x = x - 1;
}
if (x <= map.x && x >= 0) {
pos.x = x;
}
if (y <= map.y && y >= 0) {
pos.y = y;
}
}
}
result.push({ x: pos.x, y: pos.y, direction: currentDirection });
}
console.log(result);
return result;
});;
};
calculateInput()
/*
5 5
1 2 N
LFLFLFLFF
3 3 E
FFRFFRFRRF
1 2 S
FFRFFRFRRF
3 3 W
LFLFLFLFF
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment