Add solution for day 9
This commit is contained in:
1 parent
4805235f78
commit
35a596b0cb
4 files changed
+247
No files matched your search
Executable
+70
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
|
||||
def risk_level(m, x, y):
|
||||
adj = []
|
||||
if x-1 > -1:
|
||||
adj.append(m[x-1][y])
|
||||
try: adj.append(m[x+1][y])
|
||||
except IndexError: pass
|
||||
if y-1 > -1:
|
||||
adj.append(m[x][y-1])
|
||||
try: adj.append(m[x][y+1])
|
||||
except IndexError: pass
|
||||
|
||||
for a in adj:
|
||||
if a <= m[x][y]:
|
||||
return 0
|
||||
return m[x][y] + 1
|
||||
|
||||
def basin(m, x, y):
|
||||
while (x,y) not in bas:
|
||||
adj = {}
|
||||
adj[(0,0)] = m[x][y]
|
||||
if x-1 > -1:
|
||||
adj[(-1,0)] = m[x-1][y]
|
||||
try: adj[(1,0)] = m[x+1][y]
|
||||
except IndexError: pass
|
||||
if y-1 > -1:
|
||||
adj[(0,-1)] = m[x][y-1]
|
||||
try: adj[(0,1)] = m[x][y+1]
|
||||
except IndexError: pass
|
||||
|
||||
mi = min(adj.items(),key=lambda x: x[1])
|
||||
|
||||
x += mi[0][0]
|
||||
y += mi[0][1]
|
||||
bas[(x,y)] += 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
lines = open(sys.argv[1]).read().strip('\n\n').split('\n') # or split \n\n or sth similar
|
||||
mp = [[int(i) for i in l] for l in lines]
|
||||
|
||||
bas = {}
|
||||
risk = 0
|
||||
for x in range(len(mp)):
|
||||
for y in range(len(mp[0])):
|
||||
r = risk_level(mp, x, y)
|
||||
risk += r
|
||||
if r > 0:
|
||||
bas[(x,y)] = 0
|
||||
|
||||
|
||||
for x in range(len(mp)):
|
||||
for y in range(len(mp[0])):
|
||||
if mp[x][y] != 9:
|
||||
basin(mp, x, y)
|
||||
|
||||
b = sorted(bas.values(), reverse=True)
|
||||
|
||||
# challenge 1
|
||||
res1 = str(risk)
|
||||
print("challenge 1:" +"\n" + res1 + "\n")
|
||||
|
||||
# challenge 2
|
||||
|
||||
res2 = str(b[0]*b[1]*b[2])
|
||||
print("challenge 2:" +"\n" + res2 + "\n")
|
||||
|
||||
Reference in new issue
Block a user