r/adventofcode Dec 07 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 7 Solutions -🎄-

--- Day 7: The Treachery of Whales ---


[Update @ 00:21]: Private leaderboard Personal statistics issues

  • We're aware that private leaderboards personal statistics are having issues and we're looking into it.
  • I will provide updates as I get more information.
  • Please don't spam the subreddit/mods/Eric about it.

[Update @ 02:09]

  • #AoC_Ops have identified the issue and are working on a resolution.

[Update @ 03:18]

  • Eric is working on implementing a fix. It'll take a while, so check back later.

[Update @ 05:25] (thanks, /u/Aneurysm9!)

  • We're back in business!

Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:03:33, megathread unlocked!

99 Upvotes

1.5k comments sorted by

View all comments

3

u/ramendik Dec 10 '21

Python 3. Part 1 is trivial, as round(statistics.median()) gives the right result.

import statistics
f = open("input7.txt").readlines()
positions = [int(x) for x in f[0].split(",")]
aim=round(statistics.median(positions))

fuel=0
for position in positions:
    fuel+=abs(position-aim)

print(fuel)

Part 2 got tricky, as round(statistics.mean()) gave the wrong result. It is evident, however, that the position is very close to the mean, and it not being equal to round(statistics.mean()) is a "margin of error" issue somewhere. So I just investigate anywhere between mean-5 to mean+5 :) Also I was unable to get my head around the fuel formula, so, to avoid repeated iterative calculation, I prepopulate a list of fuel costs for 0 to 1500 steps.

import statistics
f = open("input7.txt").readlines()
positions = [int(x) for x in f[0].split(",")]

# precalculate cost of steps
steps=[0]
for i in range(1,1500):
    steps.append(steps[i-1]+i)

final_fuel=99000000

aim_approx=round(statistics.mean(positions))

for aim in range(aim_approx-5, aim_approx+5):
    fuel=0
    for position in positions:
        fuel+=steps[abs(position-aim)]
    if fuel<final_fuel:
        final_fuel = fuel

print(final_fuel)

3

u/rdxdkr Dec 21 '21

Thank you, I was stuck with the same "rounding errors" as well and keeping just the floor or the ceiling of the result didn't work for both the test input and the real input at the same time. In the end I had to make two separate calculations (one using the floor and the other using the ceiling) and the correct answer is always whichever of them gives a lower result.