day2, example ok

This commit is contained in:
efim 2023-12-02 16:05:32 +00:00
parent bdcdc1cdb6
commit 7e06806a2b
3 changed files with 110 additions and 5 deletions

100
day2/day-two.go Normal file
View File

@ -0,0 +1,100 @@
package day2
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
var Restriction map[string]int = map[string]int{
"red": 12,
"green": 13,
"blue": 14,
}
type Game struct {
Num int
Sets [3]map[string]int
}
// now i need to encode the restriction,
// code 'compare game to restriction'
// scan though input lines, keep only numbers of games that pass the restriction, or rather sum them
func Run() int {
filename := "./day2/example"
file, err := os.Open(filename)
if err != nil {
panic(fmt.Sprintf("error opening file", filename))
}
defer file.Close()
scanner := bufio.NewScanner(file)
result := 0
for scanner.Scan() {
line := scanner.Text()
game := ReadLine(line)
log.Printf("reading %s got game %+v it is %t", line, game, game.isPossible(Restriction))
if game.isPossible(Restriction) {
result += game.Num
}
}
return result
}
func (g Game)isPossible(restriction map[string]int) bool {
for color, maxAmount := range restriction {
for _, set := range g.Sets {
seenAmount, found := set[color]
if found && seenAmount > maxAmount {
return false
}
}
}
return true
}
func ReadLine(line string) Game {
result := Game{}
infoIndex := strings.IndexRune(line, ':')
gameTitle := line[0:infoIndex]
titleNumStr := strings.Split(gameTitle, " ")[1]
titleNum, err := strconv.Atoi(titleNumStr)
if err != nil {
panic(fmt.Sprintf("error getting game number from %s\n", line))
}
result.Num = titleNum
setsLints := strings.Split(line[infoIndex+1:], ";")
for i, set := range setsLints {
result.Sets[i] = readSet(set)
}
return result
}
// line like this
// 8 green, 6 blue, 20 red
func readSet(setLine string) map[string]int {
result := make(map[string]int)
itemLines := strings.Split(setLine, ",")
for _, line := range itemLines {
keyValue := strings.Split(strings.Trim(line, " "), " ")
if len(keyValue) != 2 {
panic(fmt.Sprintf("part '%s' of '%s' was of wrong lenght! %+v len is %d", line, setLine, keyValue, len(keyValue)))
}
num, err := strconv.Atoi(keyValue[0])
if err != nil {
panic(fmt.Sprint(setLine, line, err))
}
result[keyValue[1]] = num
}
return result
}

5
day2/example Normal file
View File

@ -0,0 +1,5 @@
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green

10
main.go
View File

@ -1,13 +1,13 @@
package main
import (
"fmt"
"log"
dayone "sunshine.industries/aoc2023/day1"
"sunshine.industries/aoc2023/day2"
)
func main() {
s := "yoyo!"
fmt.Printf("hello, %s\n", s)
dayone.Run()
log.Print("> starting run:")
result := day2.Run()
log.Printf("day2 result: %d", result)
}