-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday10Part1.js
75 lines (68 loc) · 2.21 KB
/
day10Part1.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
function readInput(fileName) {
const fs = require('fs');
const inputArray = [];
try {
const data = fs.readFileSync(fileName, 'UTF-8');
const lines = data.split(/\r?\n/);
lines.forEach((line) => {
inputArray.push(line);
});
} catch (err) {
console.error(err);
}
console.log(inputArray);
return inputArray;
}
function checkBrackets(fileName) {
const bracketArray = readInput(fileName); // I should not have named it this
const illegalCharacters = [];
let matchingBracketObject = {
'\(' : '\)',
'\[' : '\]',
'\{' : '\}',
'\<' : '\>'
};
bracketArray.forEach(line => {
let bracketQueue = [];
// iterate through characters
for (let i in line) {
// for each opening bracket, add to queue of brackets that need matching
// for each closing bracket, deque - if the next to deque is not matching, add to illegal characters
// (might be best to use push/pop)
if (line[i] === '\{' || line[i] === '\(' || line[i] === '\<' || line[i] === '\[') {
bracketQueue.push(line[i]);
console.log('bracketQueue', bracketQueue);
} else {
// current bracket is not an opening bracket, so check it matches the last opening bracket
const lastOpeningBracket = bracketQueue.pop();
if (matchingBracketObject[lastOpeningBracket] !== line[i]) {
illegalCharacters.push(line[i]);
return;
}
}
}
});
console.log(illegalCharacters);
return illegalCharacters;
}
function addUpScore(fileName) {
const illegalCharacters = checkBrackets(fileName);
const scores = {
'\)' : 3,
'\]' : 57,
'\}' : 1197,
'\>' : 25137
};
let totalScore = 0;
illegalCharacters.forEach(character => {
totalScore+=scores[character];
});
return totalScore;
}
function runTests(fileName) {
readInput(fileName);
checkBrackets(fileName);
console.log(addUpScore(fileName));
}
// runTests('day10TestInput.txt'); // 26397
runTests('day10Input.txt'); // 394647