Day 2b
This commit is contained in:
parent
95491846f9
commit
7403ce8e72
|
@ -58,25 +58,38 @@ func isGameValid(game Game) bool {
|
|||
return true
|
||||
}
|
||||
|
||||
func ScanFile(file *os.File) (int, error) {
|
||||
func power(game Game) int {
|
||||
var red, green, blue int
|
||||
for _, set := range game.sets {
|
||||
red = max(red, set.red)
|
||||
green = max(green, set.green)
|
||||
blue = max(blue, set.blue)
|
||||
}
|
||||
return red * green * blue
|
||||
}
|
||||
|
||||
func ScanFile(file *os.File) (int, int, error) {
|
||||
scanner := bufio.NewScanner(file)
|
||||
sum := 0
|
||||
var idSum, powerSum int
|
||||
for scanner.Scan() {
|
||||
if game := parseGame(scanner.Text()); isGameValid(game) {
|
||||
sum += game.id
|
||||
game := parseGame(scanner.Text())
|
||||
if isGameValid(game) {
|
||||
idSum += game.id
|
||||
}
|
||||
powerSum += power(game)
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return 0, err
|
||||
return 0, 0, err
|
||||
}
|
||||
return sum, nil
|
||||
return idSum, powerSum, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
sum, err := ScanFile(os.Stdin)
|
||||
idSum, powerSum, err := ScanFile(os.Stdin)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Invalid input: %s\n", err)
|
||||
return
|
||||
}
|
||||
fmt.Println(sum)
|
||||
fmt.Println(idSum)
|
||||
fmt.Println(powerSum)
|
||||
}
|
|
@ -6,26 +6,21 @@ import (
|
|||
)
|
||||
|
||||
func TestScanFile(t *testing.T) {
|
||||
cases := []struct {
|
||||
inFile string;
|
||||
want int;
|
||||
}{
|
||||
{"input1.txt", 8},
|
||||
}
|
||||
inFile := "input.txt"
|
||||
want1 := 8
|
||||
want2 := 2286
|
||||
|
||||
for _, c := range cases {
|
||||
f, err := os.Open(c.inFile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := os.Open(inFile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := ScanFile(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if got != c.want {
|
||||
t.Errorf("ScanFile(%q) == %d, want %d", c.inFile, got, c.want)
|
||||
}
|
||||
got1, got2, err := ScanFile(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if got1 != want1 || got2 != want2 {
|
||||
t.Errorf("ScanFile(%q) == %d, %d, want %d, %d", inFile, got1, got2, want1, want2)
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue