forked from klauvi/AdventOfCode2018
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.js
67 lines (57 loc) · 1.45 KB
/
day2.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
const fs = require('fs'); // Idea of using fs borrowed from @fhinkel
const start = new Date().getTime();
const getData = () => {
const input = fs.readFileSync('./day2.txt');
return input.toString().split('\n');
};
const input = getData();
const [double, triple] = input.reduce(
(acc, word) => {
const pairs = word
.split('')
.sort()
.join('')
.match(/(.)\1*/g); // Learned from @pete_tnt sorting string and using regex to get array with each char
if (pairs.some(letter => letter.length === 2)) {
acc[0]++;
}
if (pairs.some(letter => letter.length === 3)) {
acc[1]++;
}
return acc;
},
[0, 0]
);
console.log('Answer1:', double * triple);
const int = new Date().getTime();
input.forEach(word => {
input.forEach(word2 => {
let diff = 0;
for (let i = 0; i < word.length; i++) {
if (word[i] !== word2[i]) {
diff++;
}
}
if (diff === 1) {
let common = [];
for (let i = 0; i < word.length; i++) {
if (word[i] === word2[i]) {
common.push(word[i]);
}
}
console.log('Answer2:', common.join(''));
}
});
});
const end = new Date().getTime();
console.log(`Finished in ${end - start}ms`);
console.log(`First part in ${int - start}ms`);
console.log(`Second part in ${end - int}ms`);
/*
Answer1: 7776
Answer2: wlkigsqyfecjqqmnxaktdrhbz
Answer2: wlkigsqyfecjqqmnxaktdrhbz
Finished in 40ms
First part in 10ms
Second part in 30ms
*/