Advent of Code 2021 Python Solution: Day 9
Viper
Posted on December 9, 2021
First part was not much harder to crack but it still took plenty of time. But second part was tricky.
Part 1
import numpy as np
data,data1 = get_data(day=9)
dl = len(data1[0])
dt = np.array([int(d) for dt in data1 for d in dt])
dt = dt.reshape(-1, dl)
nums = []
pos = []
dc = len(dt[0])
dr = len(dt)
for r in range(len(dt)):
for c in range(len(dt[0])):
if r==0:
if c==0:
if dt[r,c]<dt[r+1, c] and dt[r,c]<dt[r, c+1]:
nums.append(dt[r,c])
pos.append((r,c))
elif c==dc-1:
if dt[r,c]<dt[r+1, c] and dt[r,c]<dt[r, c-1]:
nums.append(dt[r,c])
pos.append((r,c))
else:
if dt[r,c]<dt[r+1, c] and dt[r,c]<dt[r, c+1] and dt[r,c]<dt[r, c-1]:
nums.append(dt[r,c])
pos.append((r,c))
elif r==dr-1:
if c==0:
if dt[r,c]<dt[r-1, c] and dt[r,c]<dt[r, c+1]:
nums.append(dt[r,c])
pos.append((r,c))
elif c==dc-1:
if dt[r,c]<dt[r-1, c] and dt[r,c]<dt[r, c-1]:
nums.append(dt[r,c])
pos.append((r,c))
else:
if dt[r,c]<dt[r-1, c] and dt[r,c]<dt[r, c+1] and dt[r,c]<dt[r, c-1]:
nums.append(dt[r,c])
pos.append((r,c))
else:
if c==0:
if dt[r,c]<dt[r-1, c] and dt[r,c]<dt[r, c+1] and dt[r,c]<dt[r+1, c]:
nums.append(dt[r,c])
pos.append((r,c))
elif c==dc-1:
if dt[r,c]<dt[r-1, c] and dt[r,c]<dt[r, c-1] and dt[r,c]<dt[r+1, c]:
nums.append(dt[r,c])
pos.append((r,c))
else:
if dt[r,c]<dt[r-1, c] and dt[r,c]<dt[r, c+1] and dt[r,c]<dt[r, c-1] and dt[r,c]<dt[r+1, c]:
nums.append(dt[r,c])
pos.append((r,c))
nums
Part 2
I thought I had to use some sort of Searching algorithm like DFS or BFS but I found a solution on StackOverflow using NumPy.
from scipy import ndimage
label, num_label = ndimage.label(dt < 9)
size = np.bincount(label.ravel())
top3 = sorted(size[1:], reverse=True)[:3]
print(np.prod(top3))
Why not read more?
- Gesture Based Visually Writing System Using OpenCV and Python
- Gesture Based Visually Writing System: Adding Visual User Interface
- Gesture Based Visually Writing System: Adding Virtual Animationn, New Mode and New VUI
- Gesture Based Visually Writing System: Add Slider, More Colors and Optimized OOP code
- Gesture Based Visually Writing System: A Web App
- Contour Based Game: Break The Bricks
- Linear Regression from Scratch
- Writing Popular ML Optimizers from Scratch
- Feed Forward Neural Network from Scratch
- Convolutional Neural Networks from Scratch
- Writing a Simple Image Processing Class from Scratch
- Deploying a RASA Chatbot on Android using Unity3d
- Naive Bayes for text classifications: Scratch to Framework
- Simple OCR for Devanagari Handwritten Text
💖 💪 🙅 🚩
Viper
Posted on December 9, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.