From 3555be54c2abb8d5ece008a60dbdfbde0ffbddd7 Mon Sep 17 00:00:00 2001 From: Alex Pickering Date: Fri, 7 Feb 2025 12:49:48 -0600 Subject: inital commit --- 08/1.lua | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 08/1.lua (limited to '08/1.lua') diff --git a/08/1.lua b/08/1.lua new file mode 100644 index 0000000..326b8c4 --- /dev/null +++ b/08/1.lua @@ -0,0 +1,49 @@ +local heights = {} + +for line in io.lines() do + local trees = {} + line:gsub("%d",function(t) + local tree = { + height=tonumber(t), + visible={up=false,down=false,left=false,right=false}, + } + table.insert(trees,tree) + end) + table.insert(heights,trees) +end +local nrow,ncol = #heights, #heights[1] +for i = 1,nrow do + heights[i][1].visible.left = true + heights[i][ncol].visible.right = true +end +for i = 1,ncol do + heights[1][i].visible.up = true + heights[nrow][i].visible.down = true +end +local total_visible = (nrow*2) + (ncol*2) - 4 +local directions = {up={1,0},down={-1,0},left={0,1},right={0,-1}} +local function calc_visible(row,col) + local t = heights[row][col] + for name,direction in pairs(directions) do + local i,j = row - direction[1], col - direction[2] + while heights[i] and heights[i][j] do + if t.height > heights[i][j].height and heights[i][j].visible[name] then + t.visible[name] = true + break + elseif t.height <= heights[i][j].height then + t.visible[name] = false + break + end + i,j = i - direction[1], j - direction[2] + end + end + if t.visible.left or t.visible.right or t.visible.up or t.visible.down then + total_visible = total_visible + 1 + end +end +for row = 2, nrow-1 do + for col = 2, ncol-1 do + calc_visible(row,col) + end +end +print(total_visible) -- cgit v1.2.3-70-g09d2