20
Advent of Code 2021: Day 07 with Python, cheating by using scipy
The number is again, comma-separated, so np.loadtxt()
does the job
from numpy import np
pos = np.loadtxt("day_7.txt", delimiter=",")
So....this is where I cheat. I'd like to get the job done quickly and go about my day. Python has some great libraries for data science, like scipy
which has a nice selection of optimizers. We can use one of them.
The problem boils down to an optimization problem where we are to minimize the distance between a collection of 1D points and some target point. We're trying to minimize the sum of target - position
for each of the points.
from scipy.optimize import minimize_scalar
res = minimize_scalar(lambda x: np.abs(round(x)-pos).sum())
Job done.
Part 2 tells us the cost function isn't linear target - position
but is triangle numbers n(n+1)
so we simply adjust our cost function accordingly:
res = minimize_scalar(lambda x: (np.abs(round(x)-pos)*(np.abs(round(x)-pos)+1)/2).sum())
import numpy as np
from scipy.optimize import minimize_scalar
pos = np.loadtxt("day_7.txt", delimiter=",", dtype="int32")
res = minimize_scalar(lambda x: np.abs(round(x)-pos).sum())
print("Part 1 result:", round(res.fun))
res = minimize_scalar(lambda x: (np.abs(round(x)-pos)*(np.abs(round(x)-pos)+1)/2).sum())
print("Part 2 result:", round(res.fun))
20