Advent of Code occurs at Dec 01 to 25 where each day, you will need to solve a puzzle. It is Festival and the problem statement is mostly related to Christmas.
Day 08 - Treetop Tree House
https://adventofcode.com/2022/day/8
Q1
import sys
file1 = open(sys.argv[1], "r")
data = []
while True:
line = file1.readline().strip()
if not line:
break
data.append(list(line))
# print(data)
rows = len(data)
cols = len(data[0])
ans = 0
def vis(r, c):
global rows, cols, data
x = data[r][c]
rr = r - 1
while rr >= 0 and data[rr][c] < x:
rr -= 1
if rr < 0:
return True
rr = r + 1
while rr < rows and data[rr][c] < x:
rr += 1
if rr == rows:
return True
cc = c - 1
while cc >= 0 and data[r][cc] < x:
cc -= 1
if cc < 0:
return True
cc = c + 1
while cc < cols and data[r][cc] < x:
cc += 1
if cc == cols:
return True
return False
for r in range(rows):
for c in range(cols):
if r == 0 or c == 0 or r == rows - 1 or c == cols - 1 or vis(r, c):
ans += 1
Q2
import sys
file1 = open(sys.argv[1], "r")
data = []
while True:
line = file1.readline().strip()
if not line:
break
data.append(list(line))
# print(data)
rows = len(data)
cols = len(data[0])
ans = 0
def compute_score(r, c):
global rows, cols, data
x = data[r][c]
score = 1
rr = r - 1
while rr >= 0 and data[rr][c] < x:
rr -= 1
if rr < 0:
rr = 0
score *= (r - rr)
rr = r + 1
while rr < rows and data[rr][c] < x:
rr += 1
if rr == rows:
rr = rows - 1
score *= (rr - r)
cc = c - 1
while cc >= 0 and data[r][cc] < x:
cc -= 1
if cc < 0:
cc = 0
score *= (c - cc)
cc = c + 1
while cc < cols and data[r][cc] < x:
cc += 1
if cc == cols:
cc = cols - 1
score *= (cc - c)
return score
for r in range(rows):
for c in range(cols):
if not (r == 0 or c == 0 or r == rows - 1 or c == cols - 1):
ans = max(ans, compute_score(r, c))
Easy to parse input. Problem easy to understand. However, took me a while to figure out the errors in counting the trees!