-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpuzzle2a.js
More file actions
73 lines (64 loc) · 2.39 KB
/
puzzle2a.js
File metadata and controls
73 lines (64 loc) · 2.39 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
const input = require('./input/puzzle2a_input.json');
function count_letters(string, minimum_count){
return new Promise(function(resolve, reject){
const letter_count = {};
//loop through and count each occurence of each letter and save it in an object
for (let i = 0; i < string.length; i++) {
const element = string[i];
if (element in letter_count) {
letter_count[element]++;
} else {
letter_count[element] = 1;
}
}
// see if any of the letters have a count equal to the minimum_count param
// a separate for loop is used because you don't want to count false positives.
for(let key in letter_count){
const letter = letter_count[key];
if (letter == minimum_count) {
// call promise resolve method to exit the loop and return the boolean.
resolve(true);
}
};
resolve(false);
});
}
function get_checksum(input){
return new Promise((resolve, reject)=>{
const twos = [];
const threes = [];
// set up all the count_letter promises
for (let i = 0; i < input.length; i++) {
const string = input[i];
twos.push(count_letters(string, 2))
threes.push(count_letters(string, 3));
}
Promise.all(twos).then((two_vals)=>{
// when all the 2 letter promises return count how many trues you have
let two_count = 0
for (let t = 0; t < two_vals.length; t++) {
if(two_vals[t]){
two_count++;
}
}
console.log(two_count);
Promise.all(threes).then((three_vals)=>{
// when all the 3 letter promises return count how many trues you have
let three_count= 0
for (let t = 0; t < three_vals.length; t++) {
if(three_vals[t]){
three_count++;
}
}
console.log(three_count);
// we have all the counts therefore resolve with the checksum
resolve(two_count * three_count);
});
}).catch((err)=>{
console.log(err);
});
});
}
get_checksum(input).then((res)=>{
console.log("Checksum: ", res)
});