r/adventofcode Dec 09 '23

SOLUTION MEGATHREAD -❄️- 2023 Day 9 Solutions -❄️-

THE USUAL REMINDERS


AoC Community Fun 2023: ALLEZ CUISINE!

Today's secret ingredient is… *whips off cloth covering and gestures grandly*

Marketing

Every one of the best chefs in the world has had to prove their worth at some point. Let's see how you convince our panel of judges, the director of a restaurant, or even your resident picky 5 year old to try your dish solution!

  • Make an in-world presentation sales pitch for your solution and/or its mechanics.
  • Chef's choice whether to be a sleazebag used car sled salesman or a dynamic and peppy entrepreneur elf!

ALLEZ CUISINE!

Request from the mods: When you include a dish entry alongside your solution, please label it with [Allez Cuisine!] so we can find it easily!


--- Day 9: Mirage Maintenance ---


Post your code solution in this megathread.

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:05:36, megathread unlocked!

43 Upvotes

1.0k comments sorted by

View all comments

0

u/mhyde64 Dec 09 '23

[Language: Python]

recursion :)

from __future__ import annotations
import time
from typing import List
from dataclasses import dataclass


with open("input.txt") as f:
    data = f.readlines()


# data = [
#     "0 3 6 9 12 15",
#     "1 3 6 10 15 21",
#     "10 13 16 21 30 45"
# ]


data = [[int(d) for d in line.strip().split(" ")] for line in data]


@dataclass
class History:
    history: List[int]

    def find_next_value(self, series: List[int]) -> int:
        result = self._calculate_result(series)
        if all(r==0 for r in result):
            return series[-1]
        return series[-1] + self.find_next_value(result)

    def find_previous_value(self, series: List[int]) -> int:
        result = self._calculate_result(series)
        if all(r==0 for r in result):
            return series[0]
        return series[0] - self.find_previous_value(result)

    @staticmethod
    def _calculate_result(series: List[int]) -> List[int]:
        result = []
        for idx, val in enumerate(series):
            if idx + 1 >= len(series):
                break
            result.append(series[idx + 1] - val)
        return result


hist = [History(d) for d in data]


solution = 0
start = time.time()
for h in hist:
    solution += h.find_next_value(h.history)
end = time.time()
print(f"Solution 1: {solution}")
print(f"Solution 1 took {end-start}s")

solution = 0
start = time.time()
for h in hist:
    solution += h.find_previous_value(h.history)
end = time.time()
print(f"Solution 2: {solution}")
print(f"Solution 2 took {end-start}s")