From 561b10916db66e1a3da47cd50a416d2f59e37667 Mon Sep 17 00:00:00 2001 From: David Ashby Date: Sun, 3 Dec 2023 20:57:52 -0500 Subject: [PATCH] a little more refactoring --- 03/main.go | 66 +++++++++++++++++++++--------------------------------- 1 file changed, 26 insertions(+), 40 deletions(-) diff --git a/03/main.go b/03/main.go index 6b7f0fc..1af0794 100644 --- a/03/main.go +++ b/03/main.go @@ -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 } } }