DEV Community is a community of 788,395 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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

Part 1

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

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())

Full Code

import numpy as np
from scipy.optimize import minimize_scalar