Browse Source

complete day 2 part 2

master
Alexander Avery 1 year ago
parent
commit
8f3947341e
  1. 39
      day02.go
  2. 13
      main_test.go

39
day02.go

@ -8,7 +8,9 @@ import (
"strings"
)
func validgame(totalred, totalgreen, totalblue int, r io.Reader) bool {
var replacer = strings.NewReplacer(",", " ", ";", " ")
func maxgame(r io.Reader) (red, green, blue int) {
scanner := bufio.NewScanner(r)
scanner.Split(bufio.ScanWords)
@ -17,26 +19,26 @@ func validgame(totalred, totalgreen, totalblue int, r io.Reader) bool {
break
}
num, _ := strconv.Atoi(scanner.Text())
n, _ := strconv.Atoi(scanner.Text())
scanner.Scan()
switch scanner.Text() {
case "red":
if num > totalred {
return false
if n > red {
red = n
}
case "green":
if num > totalgreen {
return false
if n > green {
green = n
}
case "blue":
if num > totalblue {
return false
if n > blue {
blue = n
}
}
}
return true
return
}
type day02 struct{}
@ -48,14 +50,14 @@ func (d day02) solve1(r io.Reader) string {
totalblue = 14
gameSum = 0
scanner = bufio.NewScanner(r)
replacer = strings.NewReplacer(",", " ", ";", " ")
)
for gameN := 1; scanner.Scan(); gameN++ {
line := scanner.Text()
_, game, _ := strings.Cut(line, ": ")
sr := strings.NewReader(replacer.Replace(game))
if validgame(totalred, totalgreen, totalblue, sr) {
red, green, blue := maxgame(sr)
if red < totalred && green < totalgreen && blue < totalblue {
gameSum += gameN
}
}
@ -64,5 +66,18 @@ func (d day02) solve1(r io.Reader) string {
}
func (d day02) solve2(r io.Reader) string {
return ""
var (
sum = 0
scanner = bufio.NewScanner(r)
)
for scanner.Scan() {
line := scanner.Text()
_, game, _ := strings.Cut(line, ": ")
sr := strings.NewReader(replacer.Replace(game))
red, green, blue := maxgame(sr)
sum += (red * green * blue)
}
return fmt.Sprintf("%d", sum)
}

13
main_test.go

@ -37,8 +37,7 @@ func TestDay01(t *testing.T) {
}
func TestDay02(t *testing.T) {
ans1 := "8"
input1 := `Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
input := `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
@ -46,10 +45,18 @@ Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green`
puzzle := day02{}
res1 := puzzle.solve1(strings.NewReader(input1))
ans1 := "8"
res1 := puzzle.solve1(strings.NewReader(input))
t.Logf("day 2 solution 1: %s", res1)
if res1 != ans1 {
t.Errorf("day 2 solution 1 = %s; wanted %s", res1, ans1)
}
ans2 := "2286"
res2 := puzzle.solve2(strings.NewReader(input))
t.Logf("day 2 solution 2: %s", res2)
if res2 != ans2 {
t.Errorf("day 2 solution 2 = %s; wanted %s", res2, ans2)
}
}

Loading…
Cancel
Save