-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (70 loc) · 2.28 KB
/
main.go
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
80
81
82
83
84
package main
import (
"regexp"
"strings"
"github.com/danvolchek/AdventOfCode/lib"
)
type happinessChange struct {
target, neighbor string
value int
}
var parseRegExp = regexp.MustCompile(`(.*) would (.*) (.*) happiness units by sitting next to (.*)\.`)
func parse(parts []string) happinessChange {
var multiplier int
switch parts[1] {
case "gain":
multiplier = 1
case "lose":
multiplier = -1
default:
panic(parts)
}
return happinessChange{
target: parts[0],
neighbor: parts[3],
value: multiplier * lib.Atoi(parts[2]),
}
}
func solve(changes []happinessChange) int {
peopleMap := map[string]map[string]int{}
for _, change := range changes {
if _, ok := peopleMap[change.target]; !ok {
peopleMap[change.target] = map[string]int{}
}
peopleMap[change.target][change.neighbor] = change.value
}
people := lib.Keys(peopleMap)
calcHappy := func(seatingArrangement []string) int {
total := 0
for i := range seatingArrangement {
total += peopleMap[seatingArrangement[i]][seatingArrangement[(i+1)%len(peopleMap)]]
total += peopleMap[seatingArrangement[i]][seatingArrangement[(i-1+len(peopleMap))%len(peopleMap)]]
}
return total
}
seatingArrangements := lib.Permutations(people)
happinessForArrangements := lib.Map(seatingArrangements, calcHappy)
return lib.Max(happinessForArrangements...)
}
func main() {
solver := lib.Solver[[]happinessChange, int]{
ParseF: lib.ParseLine(lib.ParseRegexp(parseRegExp, parse)),
SolveF: solve,
}
var testCase = `
Alice would gain 54 happiness units by sitting next to Bob.
Alice would lose 79 happiness units by sitting next to Carol.
Alice would lose 2 happiness units by sitting next to David.
Bob would gain 83 happiness units by sitting next to Alice.
Bob would lose 7 happiness units by sitting next to Carol.
Bob would lose 63 happiness units by sitting next to David.
Carol would lose 62 happiness units by sitting next to Alice.
Carol would gain 60 happiness units by sitting next to Bob.
Carol would gain 55 happiness units by sitting next to David.
David would gain 46 happiness units by sitting next to Alice.
David would lose 7 happiness units by sitting next to Bob.
David would gain 41 happiness units by sitting next to Carol.
`
solver.Expect(strings.TrimSpace(testCase), 330)
solver.Verify(618)
}