-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday13.js
56 lines (52 loc) · 1.88 KB
/
day13.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
// problem: http://adventofcode.com/day/13
// input: http://adventofcode.com/day/13/input
var effect = {}; // key = affected, value = map of neighbor to effect
function addEffect(person, neighbor, effectOnPerson) {
if (!effect[person]) {
effect[person] = {};
}
effect[person][neighbor] = effectOnPerson;
}
function parseLine(s) {
if (!s) { return; }
var headNeighbor = s.split(' happiness units by sitting next to ');
var personEffect = headNeighbor[0].split(' would ');
var person = personEffect[0];
var directionMagnitude = personEffect[1].split(' ');
var direction = directionMagnitude[0] === 'gain' ? 1 : -1;
var magnitude = Number.parseInt(directionMagnitude[1]);
var effectOnPerson = direction * magnitude;
var neighbor = headNeighbor[1].slice(0,-1); // trim trailing .
addEffect(person, neighbor, effectOnPerson);
}
var inputs = document.body.innerText.split('\n');
for (var i = 0; i < inputs.length; i++) {
parseLine(inputs[i]);
}
function neighborEffect(a, b) {
return effect[a][b] + effect[b][a];
}
function bestEffect(currentEffect, seated, unseated, partb) {
if (unseated.length < 1) {
if (partb) { // insert myself for no effect between ends
return currentEffect;
}
// close loop at each end
return currentEffect + neighborEffect(seated[0], seated[seated.length-1]);
}
var best = -Infinity;
var j;
for (j = 0; j<unseated.length; j++) {
var nextEffect = (seated.length === 0) ? 0 : neighborEffect(seated[seated.length-1], unseated[j]);
var nextSeated = seated.slice(0);
nextSeated.push(unseated[j]);
var nextUnseated = unseated.slice(0);
nextUnseated.splice(j, 1);
best = Math.max(best, bestEffect(currentEffect + nextEffect, nextSeated, nextUnseated, partb));
}
return best;
}
var allGuests = Object.keys(effect);
console.log(bestEffect(0, [], allGuests));
// part b
console.log(bestEffect(0, [], allGuests, true));