summaryrefslogtreecommitdiff
path: root/08/1.lua
diff options
context:
space:
mode:
authorAlex Pickering <alex@cogarr.net>2025-02-07 12:49:48 -0600
committerAlex Pickering <alex@cogarr.net>2025-02-07 12:49:48 -0600
commit3555be54c2abb8d5ece008a60dbdfbde0ffbddd7 (patch)
tree278876284d07118ecdea5c48cb6453f3122887f0 /08/1.lua
downloadadvent_of_code_2022-master.tar.gz
advent_of_code_2022-master.tar.bz2
advent_of_code_2022-master.zip
inital commitHEADmaster
Diffstat (limited to '08/1.lua')
-rw-r--r--08/1.lua49
1 files changed, 49 insertions, 0 deletions
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)