aoc2023/day-3/two.go

54 lines
1.1 KiB
Go
Raw Permalink Normal View History

2023-12-03 23:57:05 +00:00
package main
var engineParts [][]enginePart
// getGearRatio returns the product of engine parts if exactly two neighbour a gear
func getGearRatio(row, col int) (int, error) {
partsConsidered := []enginePart{}
i := row - 1
for ; i < len(engineParts) && i <= row+1; i += 1 {
if i < 0 {
continue
}
for _, enginePart := range engineParts[i] {
2023-12-04 03:13:59 +00:00
for _, digit := range enginePart.digits {
if digit.pass && digit.col == col-1 || digit.col == col || digit.col == col+1 {
partsConsidered = append(partsConsidered, enginePart)
break
2023-12-03 23:57:05 +00:00
}
}
}
}
if len(partsConsidered) == 2 {
n1, err := partsConsidered[0].realValue()
if err != nil {
return 0, err
}
n2, err := partsConsidered[1].realValue()
if err != nil {
return 0, err
}
return n1 * n2, nil
}
return 0, nil
}
// two returns the sum of all gear ratios
func two(lines []string) (int, error) {
sum := 0
for i, line := range lines {
for j, c := range line {
if rune(c) == '*' {
n, err := getGearRatio(i, j)
if err != nil {
return 0, err
}
sum += n
}
}
}
return sum, nil
}