Skip to content

Instantly share code, notes, and snippets.

@PatrickVienne
Created December 2, 2023 06:34
Show Gist options
  • Save PatrickVienne/2aec502b3eddc8acddd6143a4a315457 to your computer and use it in GitHub Desktop.
Save PatrickVienne/2aec502b3eddc8acddd6143a4a315457 to your computer and use it in GitHub Desktop.
Advent Of Code 2023 - Day 2
package d2
import (
"bufio"
"bytes"
"io"
"regexp"
"strconv"
)
func Must(err error) {
if err != nil {
panic(err)
}
}
const (
Red = 12
Green = 13
Blue = 14
)
var allowed map[string]int = map[string]int{
"red": Red,
"green": Green,
"blue": Blue,
}
func d2_1(r io.Reader) interface{} {
reNums := regexp.MustCompile(`(Game \d+: )`)
fileScanner := bufio.NewScanner(r)
fileScanner.Split(bufio.ScanLines)
possibleGamesSum := 0
counter := 0
for fileScanner.Scan() {
gamePossible := true
counter++
databytes := fileScanner.Bytes()
databytes = reNums.ReplaceAll(databytes, []byte(``))
groups := bytes.Split(databytes, []byte(`; `))
for i := range groups {
if !gamePossible {
break
}
picks := bytes.Split(groups[i], []byte(`, `))
for j := range picks {
if !gamePossible {
break
}
numCol := bytes.Split(picks[j], []byte(` `))
num, err := strconv.Atoi(string(numCol[0]))
Must(err)
limit := allowed[string(numCol[1])]
gamePossible = num <= limit
}
}
if gamePossible {
possibleGamesSum += counter
}
}
return possibleGamesSum
}
func getPower(minNums map[string]int) int {
return minNums["red"] * minNums["green"] * minNums["blue"]
}
func getSum(numbers []int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func d2_2(r io.Reader) interface{} {
reNums := regexp.MustCompile(`(Game \d+: )`)
fileScanner := bufio.NewScanner(r)
fileScanner.Split(bufio.ScanLines)
counter := 0
powers := []int{}
for fileScanner.Scan() {
minNumsPreGame := map[string]int{
"red": 0,
"green": 0,
"blue": 0,
}
counter++
databytes := fileScanner.Bytes()
databytes = reNums.ReplaceAll(databytes, []byte(``))
groups := bytes.Split(databytes, []byte(`; `))
for i := range groups {
picks := bytes.Split(groups[i], []byte(`, `))
for j := range picks {
numCol := bytes.Split(picks[j], []byte(` `))
num, err := strconv.Atoi(string(numCol[0]))
Must(err)
minNumsPreGame[string(numCol[1])] = max(minNumsPreGame[string(numCol[1])], num)
}
}
powers = append(powers, getPower(minNumsPreGame))
}
return getSum(powers)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment