advent-of-code-2021/4/part2.go
2021-12-12 11:03:48 +01:00

60 lines
1.1 KiB
Go

package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
var numbers []int
var boards []Board
var boardLines []string
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
// first line should be the numbers
if numbers == nil {
for _, n := range strings.Split(s.Text(), ",") {
val, _ := strconv.Atoi(n)
numbers = append(numbers, val)
}
s.Scan()
continue
}
if len(s.Bytes()) == 0 {
boards = append(boards, NewBoard(boardLines))
boardLines = []string{}
} else {
boardLines = append(boardLines, s.Text())
}
}
// if we have any lines left, convert them into board
if len(boardLines) > 0 {
boards = append(boards, NewBoard(boardLines))
}
for _, num := range numbers {
if len(boards) == 1 {
board := boards[0]
board.Mark(num)
fmt.Println(board.Sum() * num)
os.Exit(0)
}
// crude filter for not winning boards
var newBoards []Board
for _, board := range boards {
board.Mark(num)
if !board.CheckWin() {
newBoards = append(newBoards, board)
}
}
boards = newBoards
}
fmt.Println(":(")
}