Created
December 7, 2021 05:50
-
-
Save p7g/b0747e1ec35c514c9deb0f4c2599914a to your computer and use it in GitHub Desktop.
Optimizing the dumb way to calculate https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF
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
| from aoc import * | |
| # This function caches very well | |
| @cache | |
| def fuel_cost(diff): | |
| return sum(range(diff + 1)) | |
| data = list(map(int, data.split(","))) | |
| smallest = float('inf') | |
| result_pos = None | |
| for i in range(min(data), max(data) + 1): | |
| # Faster than sum(fuel_cost(abs(pos - i)) for pos in data) | |
| total_fuel = sum(map(fuel_cost, map(abs, map(partial(op.add, -i), data)))) | |
| if total_fuel < smallest: | |
| smallest = total_fuel | |
| result_pos = i | |
| print(result_pos, smallest) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment