-
Notifications
You must be signed in to change notification settings - Fork 0
/
day02.js
76 lines (65 loc) · 1.6 KB
/
day02.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
67
68
69
70
71
72
73
74
75
76
'use strict' // Dive! - vehicle control simulation.
const { assert, loadData, parseInt } = require('./core/utils')
const rawInput = [loadData(module.filename)]
// Simple command set.
const puzzle1 = (commands) => {
let x = 0, depth = 0
for (const [command, value] of commands) {
if (command === 'forward') {
x += value
} else if (command === 'down') {
depth += value
} else if (command === 'up') {
if ((depth -= value) < 0) {
console.log('underrun')
depth = 0
}
} else {
assert(false, 'bad command', command)
}
}
return x * depth
}
// Modified command set.
const puzzle2 = (commands) => {
let aim = 0, x = 0, depth = 0
for (const [command, value] of commands) {
if (command === 'forward') {
x += value
depth += aim * value
} else if (command === 'down') {
aim += value
} else if (command === 'up') {
aim -= value
} else {
assert(false, 'bad command', command)
}
}
return x * depth
}
const parse = (dsn) => {
let data = rawInput[dsn]
if (data && (data = data.split('\n').filter(v => Boolean(v))).length) {
return data.map(str => {
const pair = str.split(' ')
pair[1] = parseInt(pair[1])
return pair
})
}
}
rawInput[1] = `
forward 5
down 5
forward 8
up 3
down 8
forward 2`
module.exports = { parse, puzzles: [puzzle1, puzzle2] }
/*
day02, set #1
puzzle-1 ( 123 µsecs): 150 @15min
puzzle-2 ( 70 µsecs): 900 @23min
day02, set #0
puzzle-1 ( 384 µsecs): 2073315
puzzle-2 ( 391 µsecs): 1840311528
*/