]> fbox.kageds.com Git - adventofcode.git/blob - 2023/go/day04/day04.go
day07
[adventofcode.git] / 2023 / go / day04 / day04.go
1 package day04
2
3 import (
4 "math"
5 "regexp"
6 "strings"
7
8 "fmt"
9
10 "adventofcode2023/utils"
11
12 mapset "github.com/deckarep/golang-set/v2"
13 )
14
15 type Game struct {
16 ID int
17 matches int
18 count int
19 winners mapset.Set[int]
20 cards mapset.Set[int]
21 }
22
23 func Part1(input string) int {
24 games, err := parseGames(input)
25 if err != nil {
26 fmt.Println("Error:", err)
27 return -1
28 }
29
30 points := 0.0
31 for _, game := range games {
32 matches := len(game.cards.Intersect(game.winners).ToSlice())
33 if matches > 0 {
34 points += math.Pow(2, float64(matches - 1))
35 }
36 }
37 return int(points)
38 }
39
40 func Part2(input string) int {
41 games, err := parseGames(input)
42 if err != nil {
43 fmt.Println("Error:", err)
44 return -1
45 }
46
47 for i, game := range games {
48 matches := game.cards.Intersect(game.winners).ToSlice()
49 games[i].matches = len(matches)
50 games[i].count = 1
51 }
52
53 for i:=0;i<len(games);i++{
54 for j:=0;j<games[i].count;j++ {
55 for k:=1;k<=games[i].matches;k++ {
56 games[i+k].count++
57 }
58 }
59 }
60
61 cards := 0
62 for i:=0;i<len(games);i++{
63 cards += games[i].count
64 }
65 return cards
66 }
67
68 func parseGames(input string) ([]Game, error) {
69
70 var game Game
71 var games []Game
72
73 lines := strings.Split(input, "\n")
74 for _, line := range lines {
75 reID := regexp.MustCompile(`Card\s*(\d+):(.*) \| (.*)`)
76 match := reID.FindStringSubmatch(line)
77 if len(match) != 4 {
78 return games, fmt.Errorf("unable to extract game")
79 }
80
81 game.ID = utils.MustAtoi(match[1])
82 game.winners = getNumbers(match[2])
83 game.cards = getNumbers(match[3])
84
85 games = append(games, game)
86 }
87 return games, nil
88 }
89
90 func getNumbers(input string) mapset.Set[int] {
91 tokens := strings.Fields(input)
92 var numbers []int
93 for _, token := range tokens {
94 num := utils.MustAtoi(token)
95 numbers = append(numbers, num)
96 }
97 return mapset.NewSet[int](numbers...)
98 }