a little more refactoring

This commit is contained in:
David 2023-12-03 20:57:52 -05:00
parent 4e64387873
commit 561b10916d

View File

@ -45,8 +45,8 @@ type coord struct {
col int
}
func isSymbol(s schematic, row, col int) bool {
if c, ok := s[coord{row, col}]; ok {
func isSymbol(s schematic, c coord) bool {
if c, ok := s[c]; ok {
return c.symb != 0
}
return false
@ -87,20 +87,13 @@ func partOne() {
for col := 0; col <= 139; col++ {
if entry, ok := schematic[coord{row, col}]; ok && entry.symb == 0 {
part := mustAtoi(entry.num)
if isSymbol(schematic, row, col-1) {
// look behind
sum += part
}
if isSymbol(schematic, row, col+len(entry.num)) {
// look ahead
if isSymbol(schematic, coord{row, col - 1}) || isSymbol(schematic, coord{row, col + len(entry.num)}) {
// look ahead and look behind
sum += part
}
for i := -1; i < len(entry.num)+1; i++ {
// check row above and below
if isSymbol(schematic, row-1, col+i) {
sum += part
}
if isSymbol(schematic, row+1, col+i) {
if isSymbol(schematic, coord{row - 1, col + i}) || isSymbol(schematic, coord{row + 1, col + i}) {
sum += part
}
}
@ -149,38 +142,31 @@ func partTwo() {
if entry, ok := schematic[coord{row, col}]; ok && entry.symb == 0 {
offset := len(entry.num)
part := mustAtoi(entry.num)
if isSymbol(schematic, row, col-1) {
k := coord{row, col - 1}
if gears[k] != 0 {
sum += gears[k] * part
} else {
gears[k] = part
}
found := false
k := coord{}
if isSymbol(schematic, coord{row, col - 1}) {
k = coord{row, col - 1}
found = true
}
if isSymbol(schematic, row, col+offset) {
k := coord{row, col + offset}
if gears[k] != 0 {
sum += gears[k] * part
} else {
gears[k] = part
}
if isSymbol(schematic, coord{row, col + offset}) {
k = coord{row, col + offset}
found = true
}
for i := -1; i < offset+1; i++ {
if isSymbol(schematic, row-1, col+i) {
k := coord{row - 1, col + i}
if gears[k] != 0 {
sum += gears[k] * part
} else {
gears[k] = part
}
if isSymbol(schematic, coord{row - 1, col + i}) {
k = coord{row - 1, col + i}
found = true
}
if isSymbol(schematic, row+1, col+i) {
k := coord{row + 1, col + i}
if gears[k] != 0 {
sum += gears[k] * part
} else {
gears[k] = part
}
if isSymbol(schematic, coord{row + 1, col + i}) {
k = coord{row + 1, col + i}
found = true
}
}
if found {
if gears[k] == 0 {
gears[k] = part
} else {
sum += gears[k] * part
}
}
}