Browse Source

day 2 part 1

master
Alexander Avery 12 months ago
parent
commit
4c7edb987b
  1. 68
      day02.go
  2. 18
      main_test.go

68
day02.go

@ -0,0 +1,68 @@
package main
import (
"bufio"
"fmt"
"io"
"strconv"
"strings"
)
func validgame(totalred, totalgreen, totalblue int, r io.Reader) bool {
scanner := bufio.NewScanner(r)
scanner.Split(bufio.ScanWords)
for {
if !scanner.Scan() {
break
}
num, _ := strconv.Atoi(scanner.Text())
scanner.Scan()
switch scanner.Text() {
case "red":
if num > totalred {
return false
}
case "green":
if num > totalgreen {
return false
}
case "blue":
if num > totalblue {
return false
}
}
}
return true
}
type day02 struct{}
func (d day02) solve1(r io.Reader) string {
var (
totalred = 12
totalgreen = 13
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) {
gameSum += gameN
}
}
return fmt.Sprintf("%d", gameSum)
}
func (d day02) solve2(r io.Reader) string {
return ""
}

18
main_test.go

@ -35,3 +35,21 @@ func TestDay01(t *testing.T) {
t.Errorf("day 1 solution 2 = %s; wanted %s", res2, ans2)
}
}
func TestDay02(t *testing.T) {
ans1 := "8"
input1 := `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`
puzzle := day02{}
res1 := puzzle.solve1(strings.NewReader(input1))
t.Logf("day 2 solution 1: %s", res1)
if res1 != ans1 {
t.Errorf("day 2 solution 1 = %s; wanted %s", res1, ans1)
}
}

Loading…
Cancel
Save