-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
114 lines (94 loc) · 1.9 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
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
package main
import (
"fmt"
"io"
"os"
"strconv"
"strings"
"github.com/devries/advent_of_code_2021/utils"
)
func main() {
f, err := os.Open("../inputs/day04.txt")
utils.Check(err, "error opening input.txt")
defer f.Close()
r := solve(f)
fmt.Println(r)
}
// Bingo card
type Card struct {
Dim int // length of row or column
Numbers []int // Numbers on card
}
func NewCard(d int) *Card {
c := Card{d, make([]int, d*d)}
return &c
}
func (c *Card) Parse(lines []string) {
for i := 0; i < c.Dim; i++ {
sequence := strings.Fields(lines[i])
for j, s := range sequence {
n, err := strconv.Atoi(s)
utils.Check(err, "Error parsing card number")
c.Numbers[i*c.Dim+j] = n
}
}
}
// Check for Bingo
func (c *Card) Check(selections map[int]bool) bool {
// Check rows
outerRow:
for j := 0; j < c.Dim; j++ {
for i := c.Dim * j; i < c.Dim*(j+1); i++ {
if selections[c.Numbers[i]] == false {
continue outerRow
}
}
return true
}
// Check columns
outerCol:
for j := 0; j < c.Dim; j++ {
for i := j; i < c.Dim*c.Dim; i += c.Dim {
if selections[c.Numbers[i]] == false {
continue outerCol
}
}
return true
}
return false
}
func (c *Card) Score(selection map[int]bool) int {
sum := 0
for _, v := range c.Numbers {
if selection[v] == false {
sum += v
}
}
return sum
}
func solve(r io.Reader) int {
lines := utils.ReadLines(r)
pickLine := strings.Split(lines[0], ",")
picks := make([]int, 0)
for _, s := range pickLine {
v, err := strconv.Atoi(s)
utils.Check(err, "Error converting integer in pick line")
picks = append(picks, v)
}
cards := make([]*Card, 0)
for i := 2; i < len(lines); i += 6 {
c := NewCard(5)
c.Parse(lines[i : i+5])
cards = append(cards, c)
}
selected := make(map[int]bool)
for _, p := range picks {
selected[p] = true
for _, c := range cards {
if c.Check(selected) {
return c.Score(selected) * p
}
}
}
return 0
}