Skip to content

Instantly share code, notes, and snippets.

@klunkean
Created December 25, 2021 18:40
Show Gist options
  • Save klunkean/50f04682664ac6f4f4ed536ff9e6fcea to your computer and use it in GitHub Desktop.
Save klunkean/50f04682664ac6f4f4ed536ff9e6fcea to your computer and use it in GitHub Desktop.
fname = "7_input.txt"
import numpy as np
with open(fname) as f:
xi = np.array([int(c) for c in f.readline().strip().split(",")], dtype=int)
def costfun(x, xi):
return sum([sum(range(abs(x-xii)+1)) for xii in xi])
def direction(x, xi):
plus = costfun(x+1, xi)
minus = costfun(x-1, xi)
if plus > minus:
return -1
else:
return 1
N = len(xi)
# init guess
x = round(sum(xi)/N)
done = False
cost0 = costfun(x,xi)
i = 1
while not done:
x += direction(x, xi)
cost = costfun(x,xi)
print(f"Iteration {i}, Cost: {cost}")
if cost > cost0:
done = True
cost0 = cost
i+=1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment