-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday3.js
More file actions
98 lines (82 loc) · 2.31 KB
/
Copy pathday3.js
File metadata and controls
98 lines (82 loc) · 2.31 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
import fs from 'fs';
const input = fs.readFileSync('./inputs/day3.txt', 'utf8');
const lines = input.split('\n');
const exampleInput = [
'vJrwpWtwJgWrhcsFMMfFFhFp',
'jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL',
'PmmdzqPrVvPwwTWBwg',
'wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn',
'ttgJtRGJQctTZtZT',
'CrZsJsPPZsGzwwsLwLmpwMDw',
];
const findRepeat = (st) => {
const stHalf = st.length / 2;
const stLeft = st.slice(0, stHalf);
const stRight = st.slice(stHalf);
const arr1 = stLeft.split('');
const arr2 = stRight.split('');
const repeat = arr1.filter((char) => arr2.includes(char));
return [...new Set(repeat)];
};
const findPriority = (st) => {
const stHalf = st.length / 2;
const stLeft = st.slice(0, stHalf);
const stRight = st.slice(stHalf);
const arr1 = stLeft.split('');
const arr2 = stRight.split('');
const repeat = arr1.filter((char) => arr2.includes(char));
const priority = repeat.map((char) => {
const charCode = char.charCodeAt(0);
if (charCode >= 97 && charCode <= 122) {
return charCode - 96;
} else if (charCode >= 65 && charCode <= 90) {
return charCode - 38;
}
});
return [...new Set(priority)];
};
function part1(input) {
const priority = [];
lines.forEach((st) => {
const p = findPriority(st);
priority.push(p);
});
const sum = priority.reduce((acc, curr) => {
return acc + curr.reduce((a, c) => a + c, 0);
}, 0);
return sum;
}
const a1 = part1(lines);
function findCommon(arr1, arr2, arr3) {
const common = arr1.filter(
(char) => arr2.includes(char) && arr3.includes(char)
);
return [...new Set(common)];
}
function chunkArray(arr, size) {
const chunked_arr = [];
let index = 0;
while (index < arr.length) {
chunked_arr.push(arr.slice(index, size + index));
index += size;
}
return chunked_arr;
}
const arr = chunkArray(exampleInput, 3);
const inputArr = chunkArray(lines, 3);
const common = [];
inputArr.forEach((st) => {
const c = findCommon(st[0].split(''), st[1].split(''), st[2].split(''));
common.push(c);
});
const priority = common.flat().map((st) => {
const charCode = st.charCodeAt(0);
if (charCode >= 97 && charCode <= 122) {
return charCode - 96;
} else if (charCode >= 65 && charCode <= 90) {
return charCode - 38;
}
});
const sum = priority.reduce((acc, curr) => {
return acc + curr;
}, 0);