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