Created
December 5, 2016 03:48
-
-
Save MrSkinny/a1c191b6fe5d497106e7764e3271bbb8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const file = fs.readFileSync(__dirname + '/ex1-data.txt', 'utf8'); | |
const directions = file.split(',').map(i => i.trim()); | |
const Compass = { | |
MATRIX: ['N', 'E', 'S', 'W'], | |
left(start){ | |
const index = this.MATRIX.findIndex(i => i === start); | |
if (index === -1) return start; | |
if (index === 0) return this.MATRIX[3]; | |
return this.MATRIX[index - 1]; | |
}, | |
right(start){ | |
const index = this.MATRIX.findIndex(i => i === start); | |
if (index === -1) return start; | |
if (index === 3) return this.MATRIX[0]; | |
return this.MATRIX[index + 1]; | |
}, | |
}; | |
class Meeple { | |
constructor(x = 500, y = 500) { | |
this.INITIAL_X = x; | |
this.INITIAL_Y = y; | |
this.x = x; | |
this.y = y; | |
this.facing = 'N'; | |
} | |
_validateDirection(direction){ | |
return direction === 'R' || direction === 'L'; | |
} | |
_validateSpaces(spaces){ | |
return !isNaN(spaces) && spaces > 0; | |
} | |
_processOne(instruction){ | |
if (typeof instruction !== 'string') return false; | |
const direction = instruction[0]; | |
const spaces = Number(instruction.slice(1)); | |
if (!this._validateDirection(direction)) return false; | |
if (!this._validateSpaces(spaces)) return false; | |
direction === 'R' ? this.turnRight() : this.turnLeft(); | |
this.move(spaces); | |
return true; | |
} | |
turnLeft(){ | |
this.facing = Compass.left(this.facing); | |
} | |
turnRight(){ | |
this.facing = Compass.right(this.facing); | |
} | |
move(n){ | |
if (isNaN(Number(n))) return; | |
if (this.facing === 'N') this.y -= n; | |
else if (this.facing === 'E') this.x += n; | |
else if (this.facing === 'S') this.y += n; | |
else if (this.facing === 'W') this.x -= n; | |
} | |
process(instructions){ | |
const startAt = { x: this.x, y: this.y }; | |
for (let i = 0; i < instructions.length; i++){ | |
const instruction = instructions[i]; | |
if (!this._processOne(instruction)) { | |
this.x = startAt.x; | |
this.y = startAt.y; | |
return false; | |
} | |
} | |
return true; | |
} | |
shortestDistance(){ | |
let diffX, diffY; | |
diffX = this.x <= this.INITIAL_X ? this.INITIAL_X - this.x : this.x - this.INITIAL_X; | |
diffY = this.y <= this.INITIAL_Y ? this.INITIAL_Y - this.y : this.y - this.INITIAL_Y; | |
return diffX + diffY; | |
} | |
} | |
const meep = new Meeple(); | |
if (meep.process(directions)) { | |
console.log('did it!'); | |
console.log(meep.shortestDistance()); | |
} else { | |
console.log('failed!'); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment