-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathday10.js
85 lines (78 loc) · 1.86 KB
/
day10.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
77
78
79
80
81
82
83
84
85
'use strict';
const fs = require('fs');
const cl = console.log;
fs.readFile('day10.txt', 'utf-8', (err, input) => {
if (err) throw err;
let lines = input.trim().split(/\r?\n/).map(ln => [...ln]);
cl(syntaxScoring1(lines));
cl(syntaxScoring2(lines));
});
function syntaxScoring1(lines) {
return lines
.map(line => check(line))
.filter(rslt => !rslt.valid)
.reduce((sum, rslt) => sum + charScore1(rslt.char), 0);
}
function check(line, open = []) {
let remaining = line.slice(0);
if (remaining.length === 0) {
return { valid: true, open };
}
let char = remaining.shift();
let closingChar;
if (closingChar = isOpening(char)) {
open.push(closingChar);
return check(remaining, open);
}
return char === open.pop() ?
check(remaining, open) :
{ valid: false, char };
}
function isOpening(c) {
switch (c) {
case '(':
return ')';
case '[':
return ']';
case '{':
return '}';
case '<':
return '>';
default:
return false;
}
}
function charScore1(c) {
switch (c) {
case ')':
return 3;
case ']':
return 57;
case '}':
return 1197;
case '>':
return 25137;
}
}
function syntaxScoring2(lines) {
let scores = lines
.map(line => check(line))
.filter(rslt => rslt.valid)
.map(rslt =>
rslt.open.reverse()
.reduce((agg, char) => agg * 5 + charScore2(char), 0))
.sort((a, b) => a - b);
return scores[(scores.length - 1) / 2];
}
function charScore2(c) {
switch (c) {
case ')':
return 1;
case ']':
return 2;
case '}':
return 3;
case '>':
return 4;
}
}