-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtable.js
66 lines (51 loc) · 1.73 KB
/
table.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
const getPermutations = (persons) => {
const permutations = [];
const permute = (array, permutation = []) => {
if (!array.length) {
permutations.push(permutation);
return;
}
for (let i = 0; i < array.length; i++) {
const rest = [...array];
const person = rest.splice(i, 1)[0];
permute(rest, [...permutation, person]);
}
};
permute(persons, []);
return permutations;
};
const table = (input) => {
const relationships = input
.split('\n')
.map((x) => {
const relationship = x.match(/(\w+) would (\w+) (\d+) happiness units by sitting next to (\w+)\./);
return {
name: relationship[1],
change: parseInt(relationship[3]) * (relationship[2] === 'gain' ? 1 : -1),
neighbor: relationship[4],
};
})
.reduce((accumulator, currentValue) => {
if (!accumulator[currentValue.name]) {
accumulator[currentValue.name] = {};
}
accumulator[currentValue.name][currentValue.neighbor] = currentValue.change;
return accumulator;
}, {});
const happinessChanges = getPermutations(Object.keys(relationships))
.map((permutation) => {
let happinessChange = 0;
for (let i = 0; i < permutation.length; i++) {
if (typeof permutation[i + 1] !== 'undefined') {
happinessChange += relationships[permutation[i]][permutation[i + 1]] +
relationships[permutation[i + 1]][permutation[i]];
} else {
happinessChange += relationships[permutation[i]][permutation[0]] +
relationships[permutation[0]][permutation[i]];
}
}
return happinessChange;
});
return Math.max(...happinessChanges);
};
module.exports = table;