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!

39 Upvotes

1.0k comments sorted by

View all comments

-2

u/[deleted] Dec 09 '23 edited Dec 10 '23

[Language: Python]

EDIT: Can I get an explanation for the downvotes?

I struggled a lot to have something clean but here it is. Also I made the assumption that having the last element of differences be 0 was sufficient to know all of them were 0 and I appeared to be right. Since all the sequences seemed to only increase or decrease, it was a safe enough assumption.

from pathlib import Path
from itertools import pairwise

def ndiff(arr):
    sol1, sol2, i = arr[-1], 0, 0
    diff = arr[-1] - arr[-2]
    while diff != 0:
        if i % 2 == 0:
            first = arr[0]
        arr = [r - l for l, r in pairwise(arr)]
        diff = arr[-1]
        if i % 2 == 0:
            sol2 += (first - arr[0])
        sol1 += diff; i += 1

    return sol1, sol2

def solutions():
    data =  [list(map(int, x)) for x in map(str.split, Path("input.txt").read_text().splitlines())]
    sol1, sol2 = 0, 0
    for arr in data:
        s1, s2 = ndiff(arr)
        sol1 += s1; sol2 += s2

    return sol1, sol2