-
Notifications
You must be signed in to change notification settings - Fork 4
/
01-2.js
66 lines (51 loc) · 1.52 KB
/
01-2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
--- Day 1: No Time for a Taxicab ---
--- Part Two ---
Then, you notice the instructions continue on the back of the Recruiting Document. Easter Bunny HQ is actually at the first location you visit twice.
For example, if your instructions are R8, R4, R4, R8, the first location you visit twice is 4 blocks away, due East.
How many blocks away is the first location you visit twice?
*/
const TURN = {
RIGHT: 1,
LEFT: -1,
}
const FACING = {
NORTH: 0,
EAST: 1,
SOUTH: 2,
WEST: 3,
}
const initialState = {
facing: FACING.NORTH,
x: 0,
y: 0,
}
function moveAndFindIntersection(steps, initialState) {
const visited = { '0,0': true }
let state = initialState
for (let step of steps) {
state.facing = (state.facing + step.turn + 4) % 4
let dist = step.dist
for (let d = 1; d <= dist; d++) {
switch (state.facing) {
case FACING.NORTH: state.y++; break
case FACING.SOUTH: state.y--; break
case FACING.EAST: state.x++; break
case FACING.WEST: state.x--; break
}
const location = state.x + ',' + state.y
if (visited[location]) {
return state
}
visited[location] = true
}
}
}
const input = require('fs').readFileSync('01.txt', 'utf8');
const steps = input.split(', ').map(pair => ({
turn: pair[0] === 'R' ? TURN.RIGHT : TURN.LEFT,
dist: parseInt(pair.slice(1), 10),
}))
const finalState = moveAndFindIntersection(steps, initialState)
const blockDistance = Math.abs(finalState.x) + Math.abs(finalState.y)
console.log(blockDistance)