-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.js
79 lines (65 loc) · 1.58 KB
/
day7.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
76
77
78
79
const fs = require("fs");
const day7 = ()=> {
const data = fs.readFileSync("day7.txt", "utf8").trim().split("\n").map(x => x.split(" "));
const part1 = data.map(hand => get_hash(hand, false)).sort((handA, handB) => sort_hands(handA, handB)).map((hand, index) => hand[1]*(index+1)).reduce((a,b) => a+b);
const part2 = data.map(hand => get_hash(hand, true)).sort((handA, handB) => sort_hands(handA, handB)).map((hand, index) => hand[1]*(index+1)).reduce((a,b) => a+b);
return {"part 1": part1, "part 2": part2};
}
const card_values = {
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9,
T: 10,
J: 11,
Q: 12,
K: 13,
A: 14
}
const card_values_J = {
J: 0,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9,
T: 10,
Q: 11,
K: 12,
A: 13
}
const get_hash = (hand, jokers) => {
const bid = hand[1];
const cards = hand[0].split("").map(x => jokers?card_values_J[x]:card_values[x]);
const count = {};
for(let i = 0; i < 5; i++) {
count[cards[i]] = count[cards[i]]+1 || 1;
}
let j;
if(jokers) {
j = count[0];
delete count[0];
}
const hash = Object.values(count).sort((a,b)=>b-a);
if(hash.length == 0) {
hash.push(0);
}
hash[0] += jokers?(j || 0):0;
return [hash.concat(cards), bid];
}
const sort_hands = (handA, handB) => {
for(let i = 0; i < handA[0].length; i++) {
if(handA[0][i] !== handB[0][i]) {
return handA[0][i]-handB[0][i];
}
}
return 0;
}
module.exports = day7;