-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathpart-two.js
63 lines (53 loc) · 2.06 KB
/
part-two.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
const G = require('generatorics');
const { uniq } = require('lodash');
const input = require('./input');
let unique_people = uniq(input.map(p => p.person));
const happiness_lookup = {};
unique_people.forEach(person => {
happiness_lookup[person] = {
happinessChangeSittingNextTo: {},
};
});
// Add in yourself
const YOURSELF = 'You';
unique_people.push(YOURSELF);
happiness_lookup[YOURSELF] = { happinessChangeSittingNextTo: {} };
unique_people.forEach(person => {
happiness_lookup[YOURSELF].happinessChangeSittingNextTo[person] = 0;
});
input.forEach(info => {
let { person, happinessChange, sittingNextTo } = info;
happiness_lookup[person].happinessChangeSittingNextTo[sittingNextTo] = happinessChange;
// This gets set multiple times, but that is OK
happiness_lookup[person].happinessChangeSittingNextTo[YOURSELF] = 0;
});
let max_happiness = 0;
let best_seating_arrangement = '';
for (let seating_arrangement of G.permutation(unique_people)) {
let total_happiness = 0;
seating_arrangement.forEach((person, index) => {
let left, right;
if (index === 0) {
// First person
left = seating_arrangement[seating_arrangement.length - 1];
right = seating_arrangement[index + 1];
} else if (index === seating_arrangement.length - 1) {
// Last person
left = seating_arrangement[index - 1];
right = seating_arrangement[0];
} else {
left = seating_arrangement[index - 1];
right = seating_arrangement[index + 1];
}
let left_change = happiness_lookup[person].happinessChangeSittingNextTo[left];
let right_change = happiness_lookup[person].happinessChangeSittingNextTo[right];
total_happiness += left_change + right_change;
});
if (total_happiness > max_happiness) {
max_happiness = total_happiness;
best_seating_arrangement = seating_arrangement.join(',');
}
}
console.log(
`With a seating arrangment of ${best_seating_arrangement}, we max the hapiness at\n${max_happiness}`
);