60 lines
1.5 KiB
Nim
60 lines
1.5 KiB
Nim
import std/[cmdline, sequtils, strformat, strutils]
|
|
|
|
var fn: string
|
|
|
|
if paramCount() > 0:
|
|
fn = paramStr(1)
|
|
else:
|
|
fn = "input_03.txt"
|
|
|
|
var result = 0
|
|
var lines = readFile(fn).strip.splitLines
|
|
var grid = newSeqWith(lines.len, newSeq[char](lines[0].strip.len))
|
|
|
|
|
|
proc isAdjacentToSymbol(row, col: int): 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 not ch.isDigit and ch != '.':
|
|
return true
|
|
return false
|
|
|
|
|
|
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 isAdjacentToSymbol(i, j):
|
|
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 untl the end of the row
|
|
if isPartNumber:
|
|
result += number.parseInt
|
|
|
|
echo &"Result: {result}"
|