generated from devries/aoc_template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.go
143 lines (116 loc) · 2.18 KB
/
solution.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package day07p1
import (
"fmt"
"io"
"sort"
"strconv"
"strings"
"aoc/utils"
)
func Solve(r io.Reader) any {
lines := utils.ReadLines(r)
var g Game
for _, ln := range lines {
hand := NewHand(ln)
g = append(g, hand)
}
sort.Sort(g)
var sum int64
for i, v := range g {
sum += int64(i+1) * v.Bid
}
return sum
}
type HandType int64
const (
HighCard HandType = iota
OnePair
TwoPair
ThreeOfAKind
FullHouse
FourOfAKind
FiveOfAKind
)
type Hand struct {
Type HandType
Cards []rune
Bid int64
}
// Create hand by parsing line
func NewHand(ln string) *Hand {
parts := strings.Fields(ln)
cards := []rune(parts[0])
bid, err := strconv.ParseInt(parts[1], 10, 64)
utils.Check(err, "Unable to parse %s to int64", parts[1])
counts := make(map[rune]int)
for _, c := range cards {
counts[c]++
}
cardcounts := make([]int, 0, 5)
for _, v := range counts {
cardcounts = append(cardcounts, v)
}
sort.Ints(cardcounts)
var hand HandType
switch {
case equal(cardcounts, []int{5}):
hand = FiveOfAKind
case equal(cardcounts, []int{1, 4}):
hand = FourOfAKind
case equal(cardcounts, []int{2, 3}):
hand = FullHouse
case equal(cardcounts, []int{1, 1, 3}):
hand = ThreeOfAKind
case equal(cardcounts, []int{1, 2, 2}):
hand = TwoPair
case equal(cardcounts, []int{1, 1, 1, 2}):
hand = OnePair
case equal(cardcounts, []int{1, 1, 1, 1, 1}):
hand = HighCard
default:
panic(fmt.Sprintf("Unexpected card counts: %v", cardcounts))
}
return &Hand{hand, cards, bid}
}
func equal(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
type Game [](*Hand)
var cardValues = map[rune]int{
'2': 0,
'3': 1,
'4': 2,
'5': 3,
'6': 4,
'7': 5,
'8': 6,
'9': 7,
'T': 8,
'J': 9,
'Q': 10,
'K': 11,
'A': 12,
}
func (g Game) Len() int { return len(g) }
func (g Game) Swap(i, j int) { g[i], g[j] = g[j], g[i] }
func (g Game) Less(i, j int) bool {
a := g[i]
b := g[j]
if a.Type != b.Type {
return a.Type < b.Type
}
for k := 0; k < 5; k++ {
if cardValues[a.Cards[k]] != cardValues[b.Cards[k]] {
return cardValues[a.Cards[k]] < cardValues[b.Cards[k]]
}
}
return false
}