2023-12-03 13:33:19 +01:00
|
|
|
import std/[cmdline, sequtils, strformat, strutils, sugar]
|
2023-12-03 11:16:51 +01:00
|
|
|
|
2023-12-03 13:33:19 +01:00
|
|
|
proc isAdjacentToCond(grid: seq[seq[char]], row, col: int, cond: (char) -> bool): bool =
|
2023-12-03 11:16:51 +01:00
|
|
|
for i in @[row - 1, row, row + 1]:
|
|
|
|
if i < 0 or i >= grid.len:
|
|
|
|
continue
|
|
|
|
for j in @[col - 1, col, col + 1]:
|
|
|
|
if i == row and j == col:
|
|
|
|
continue
|
|
|
|
if j < 0 or j >= grid[i].len:
|
|
|
|
continue
|
|
|
|
var ch = grid[i][j]
|
2023-12-03 13:33:19 +01:00
|
|
|
if cond(ch):
|
2023-12-03 11:16:51 +01:00
|
|
|
return true
|
|
|
|
return false
|
|
|
|
|
|
|
|
|
2023-12-03 13:33:19 +01:00
|
|
|
var fn = if paramCount() > 0: paramStr(1) else: "input_03.txt"
|
|
|
|
|
|
|
|
var result = 0
|
|
|
|
var lines = readFile(fn).strip.splitLines
|
|
|
|
var grid = newSeqWith(lines.len, newSeq[char](lines[0].strip.len))
|
|
|
|
|
2023-12-03 11:16:51 +01:00
|
|
|
for i, line in lines:
|
|
|
|
for j, ch in line.strip:
|
|
|
|
grid[i][j] = ch
|
|
|
|
|
|
|
|
#echo &"Rows: {grid.len}"
|
|
|
|
#echo &"Cols: {grid[0].len}"
|
|
|
|
|
|
|
|
for i, row in grid:
|
|
|
|
var isPartNumber = false
|
|
|
|
var number = ""
|
|
|
|
|
|
|
|
for j, ch in row:
|
|
|
|
if ch.isDigit:
|
|
|
|
number &= ch
|
2023-12-03 13:33:19 +01:00
|
|
|
if isAdjacentToCond(grid, i, j, (c) => not c.isDigit and c != '.'):
|
2023-12-03 11:16:51 +01:00
|
|
|
isPartNumber = true
|
|
|
|
else:
|
|
|
|
if isPartNumber:
|
|
|
|
#echo number.parseInt
|
|
|
|
result += number.parseInt
|
2023-12-03 13:33:19 +01:00
|
|
|
#elif number.len > 0:
|
|
|
|
# echo &"Not a part number: {number.parseInt} (row {i}, col {j})"
|
|
|
|
|
2023-12-03 11:16:51 +01:00
|
|
|
number = ""
|
|
|
|
isPartNumber = false
|
|
|
|
|
2023-12-03 13:33:19 +01:00
|
|
|
# account for numbers going until the end of the row
|
2023-12-03 11:16:51 +01:00
|
|
|
if isPartNumber:
|
|
|
|
result += number.parseInt
|
|
|
|
|
|
|
|
echo &"Result: {result}"
|
2023-12-03 13:33:19 +01:00
|
|
|
|
|
|
|
case fn:
|
|
|
|
of "input_03.txt":
|
|
|
|
assert result == 559667
|
|
|
|
of "sample_input_03.txt":
|
|
|
|
assert result == 4361
|