Last active
December 7, 2021 14:59
-
-
Save kwinkunks/95340a9099ff7410dd4fa7f6434f91e9 to your computer and use it in GitHub Desktop.
A solution to AOC 2021, Day 7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def get_data(day, dataset): | |
with open(f'../js/day{day:02d}/{dataset}.txt', 'r') as f: | |
return np.array(list(map(int, f.read().split(',')))) | |
def part1(data): | |
return np.abs(data - np.median(data)).sum() | |
def part2(data): | |
points = np.arange(2000).reshape(-1, 1) # Points to test, total guess. | |
dists = np.abs(np.subtract.outer(points, data)) # Do them all at once. | |
cost = np.sum(dists * (dists + 1) / 2, axis=-1) # Triangular number formula. | |
return cost.min() | |
if __name__ == "__main__": | |
# Part 1. | |
assert part1(get_data(7, 'test')) == 37, "Part 1 failed." | |
print(f"Part 1: {part1(get_data(7, 'data')):.0f}") | |
# Part 2. | |
assert part2(get_data(7, 'test')) == 168, "Part 2 failed." | |
print(f"Part 2: {part2(get_data(7, 'data')):.0f}") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment