Created
December 1, 2016 22:11
-
-
Save Kattoor/9ababedd4debcee28a2c7e77b378255a 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 position = { x: 0, y: 0 } | |
// left up right down | |
const Dir = [ [0, 3, 1, {x: -1, y: 0}], [1, 0, 2, {x: 0, y: 1}], [2, 1, 3, {x: 1, y: 0}], [3, 2, 0, {x: 0, y: -1}]] | |
const positionHistory = [] | |
let currentDirectionIndex = 1 | |
function move(input) { | |
const dir = input[0] | |
const steps = input.substr(1) | |
currentDirectionIndex = Dir.find(direction => Dir[currentDirectionIndex][dir === 'L' ? 1 : 2] === direction[0])[0] | |
let currentDirection = Dir[currentDirectionIndex] | |
let deltaX = currentDirection[3].x | |
let deltaY = currentDirection[3].y | |
if (deltaX != 0) { | |
for (let i = 0; i < steps; i++) { | |
position.x += deltaX | |
positionHistory.push({x: position.x, y: position.y}) | |
} | |
} | |
if (deltaY != 0) { | |
for (let i = 0; i < steps; i++) { | |
position.y += deltaY | |
positionHistory.push({x: position.x, y: position.y}) | |
} | |
} | |
found = checkHistory() | |
} | |
var found | |
function checkHistory() { | |
let temp = [] | |
for (let point of positionHistory) { | |
for (let tempPoint of temp) { | |
if (tempPoint.x === point.x && tempPoint.y === point.y) | |
return point | |
} | |
temp.push(point) | |
} | |
return null | |
} | |
const inputString = "L5, R1, L5, L1, R5, R1, R1, L4, L1, L3, R2, R4, L4, L1, L1, R2, R4, R3, L1, R4, L4, L5, L4, R4, L5, R1, R5, L2, R1, R3, L2, L4, L4, R1, L192, R5, R1, R4, L5, L4, R5, L1, L1, R48, R5, R5, L2, R4, R4, R1, R3, L1, L4, L5, R1, L4, L2, L5, R5, L2, R74, R4, L1, R188, R5, L4, L2, R5, R2, L4, R4, R3, R3, R2, R1, L3, L2, L5, L5, L2, L1, R1, R5, R4, L3, R5, L1, L3, R4, L1, L3, L2, R1, R3, R2, R5, L3, L1, L1, R5, L4, L5, R5, R2, L5, R2, L1, L5, L3, L5, L5, L1, R1, L4, L3, L1, R2, R5, L1, L3, R4, R5, L4, L1, R5, L1, R5, R5, R5, R2, R1, R2, L5, L5, L5, R4, L5, L4, L4, R5, L2, R1, R5, L1, L5, R4, L3, R4, L2, R3, R3, R3, L2, L2, L2, L1, L4, R3, L4, L2, R2, R5, L1, R2" | |
const commands = inputString.split(", ") | |
for (const command of commands) { | |
move(command) | |
if (found) break | |
} | |
if (found) | |
console.log("Distance: " + (Math.abs(found.x) + Math.abs(found.y))) | |
else | |
console.log("Aww; no intersection") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment