mirror of
https://github.com/onyx-and-iris/aoc2023.git
synced 2024-11-22 10:20:48 +00:00
54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
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] {
|
|
for _, digit := range enginePart.digits {
|
|
if digit.pass && digit.col == col-1 || digit.col == col || digit.col == col+1 {
|
|
partsConsidered = append(partsConsidered, enginePart)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
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
|
|
}
|