adventofcode-2023/day_03/solution_03.nim

61 lines
1.6 KiB
Nim
Raw Permalink Normal View History

import std/[cmdline, sequtils, strformat, strutils, sugar]
proc isAdjacentToCond(grid: seq[seq[char]], row, col: int, cond: (char) -> bool): bool =
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]
if cond(ch):
return true
return false
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))
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
if isAdjacentToCond(grid, i, j, (c) => not c.isDigit and c != '.'):
isPartNumber = true
else:
if isPartNumber:
#echo number.parseInt
result += number.parseInt
#elif number.len > 0:
# echo &"Not a part number: {number.parseInt} (row {i}, col {j})"
number = ""
isPartNumber = false
# account for numbers going until the end of the row
if isPartNumber:
result += number.parseInt
echo &"Result: {result}"
case fn:
of "input_03.txt":
assert result == 559667
of "sample_input_03.txt":
assert result == 4361