generated from mariotacke/template-advent-of-code
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpart2.js
50 lines (41 loc) · 1.17 KB
/
part2.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
const characterScoreMap = new Map([
[')', 1],
[']', 2],
['}', 3],
['>', 4],
]);
const closingCharacterMap = new Map([
['(', ')'],
['[', ']'],
['{', '}'],
['<', '>'],
]);
module.exports = (input) => {
const scores = input
.split('\n')
.reduce((scores, line) => {
const characters = line.trim().split('');
const history = [];
for (let i = 0; i < characters.length; i++) {
const currentCharacter = characters[i];
if (closingCharacterMap.has(currentCharacter)) {
history.push(currentCharacter);
} else {
const lastOpeningCharacter = history.slice(-1)[0];
const lastClosingCharacter = closingCharacterMap.get(lastOpeningCharacter);
if (lastClosingCharacter === currentCharacter) {
history.pop();
} else {
return scores;
}
}
}
history.reverse();
scores.push(history.reduce((total, character) => {
return total * 5 + characterScoreMap.get(closingCharacterMap.get(character));
}, 0));
return scores;
}, [])
.sort((a, b) => a - b);
return scores.slice(Math.floor(scores.length / 2))[0];
};