-
Notifications
You must be signed in to change notification settings - Fork 0
/
day16.js
77 lines (73 loc) · 1.76 KB
/
day16.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
// problem: http://adventofcode.com/day/16
// input: http://adventofcode.com/day/16/input
var target = {
children: 3,
cats: 7,
samoyeds: 2,
pomeranians: 3,
akitas: 0,
vizslas: 0,
goldfish: 5,
trees: 3,
cars: 2,
perfumes: 1,
matches: function(sue) {
if (!sue) { return false; }
var attrs = Object.keys(sue);
for (var j = 0; j < attrs.length; j++) {
var attr = attrs[j];
if (attr === "name") {
continue;
}
if (sue[attr] !== this[attr]) {
return false;
}
}
return true;
},
retroencabulate: function(sue) {
if (!sue) { return false; }
var attrs = Object.keys(sue);
for (var j = 0; j < attrs.length; j++) {
var attr = attrs[j];
if (attr === "name") {
continue;
}
if (attr === "cats" || attr === "trees") {
if (sue[attr] <= this[attr]) {
return false;
}
} else if (attr === "pomeranians" || attr === "goldfish") {
if (sue[attr] >= this[attr]) {
return false;
}
} else if (sue[attr] !== this[attr]) {
return false;
}
}
return true;
}
};
function parseLine(s) {
if (!s) { return null; }
var name = s.split(':', 1)[0];
var attrvals = s.substr(name.length+2).split(', ');
var sue = { name: name };
for (var m = 0; m < attrvals.length; m++) {
var kv = attrvals[m].split(': ');
sue[kv[0]] = parseInt(kv[1]);
}
return sue;
}
function run(isPartB) {
var candidate;
var inputs = document.body.innerText.split('\n');
for (var i = 0; i < inputs.length; i++) {
candidate = parseLine(inputs[i]);
if (isPartB ? target.retroencabulate(candidate) : target.matches(candidate)) {
return candidate;
}
}
}
console.log(run(false));
console.log(run(true));