r/adventofcode • • Dec 05 '23

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

Preview here: https://redditpreview.com/

-❄️- 2023 Day 5 Solutions -❄️-


THE USUAL REMINDERS


AoC Community Fun 2023: ALLEZ CUISINE!

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

ELI5

Explain like I'm five! /r/explainlikeimfive

  • Walk us through your code where even a five-year old could follow along
  • Pictures are always encouraged. Bonus points if it's all pictures…

    • Emoji(code) counts but makes Uncle Roger cry 😥
  • Explain everything that you’re doing in your code as if you were talking to your pet, rubber ducky, or favorite neighbor, and also how you’re doing in life right now, and what have you learned in Advent of Code so far this year?
  • Explain the storyline so far in a non-code medium
  • Create a Tutorial on any concept of today's puzzle or storyline (it doesn't have to be code-related!)

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 5: If You Give A Seed A Fertilizer ---


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:26:37, megathread unlocked!

82 Upvotes

1.1k comments sorted by

View all comments

1

u/grendel-khan Dec 06 '23

[Language: Python3]

Part 1:

#!/usr/bin/python3

import sys


def process(num, maps):
    for stage in maps:
        for part in stage:
            if num in part["r"]:
                num += part["d"] - part["r"].start
                break
    return num


if __name__ == "__main__":
    fname = sys.argv[1]
    maps = []
    stage = -1
    lines = [line for line in open(fname, "r")]
    nums = [int(x) for x in lines[0].split(":")[1].split()]
    for line in lines[1:]:
        if ':' in line:
            stage += 1
            maps.append([])
            continue
        if line.strip() == "":
            continue
        dest, src, length = (int(x) for x in line.split())
        maps[stage].append({"r": range(src, src+length), "d": dest})
    outputs = []
    for num in nums:
        out = process(num, maps)
        print(f"mapped {num} to {out}")
        outputs.append(out)
    print(f"min={min(outputs)}")

Part 2, which gave me the wrong output for the test input, but the correct output for the real input (as of last night! should have tried it then). I wrote unit tests, and everything seems to be right. Maybe I got something wrong here, but it works and I can't find the problem, despite a lot of handwringing.

#!/usr/bin/python3

import sys


# https://stackoverflow.com/a/55272008/21639090
def range_intersect(r1, r2):
    return range(max(r1.start,r2.start), min(r1.stop,r2.stop)) or None


def process_group(stage_part, input_nums):
    """Processes a single range through a single stage-part.

    Returns the changed ranges in one list, and the unchanged ones in another.
    """
    changed, unchanged = [], []
    intersection = range_intersect(input_nums, stage_part["r"])
    if intersection is not None:
        new_start = input_nums.start - stage_part["r"].start + stage_part["d"]
        new_stop = new_start + len(intersection)
        changed.append(range(new_start, new_stop))
        # Pass through non-intersecting parts.
        if intersection.start > input_nums.start:
            unchanged.append(range(input_nums.start, intersection.start))
        if intersection.stop < input_nums.stop:
            unchanged.append(range(intersection.stop, input_nums.stop))
    else:
        unchanged.append(input_nums)
    return unchanged, changed


def process_stage(nums, stage):
    """Takes one or more ranges, splits them, checks them."""
    print(f"nums={nums}, stage={stage}")
    out_nums = []
    for part in stage:
        new_nums = []
        for group in nums:
            num, new_out_nums = process_group(part, group)
            new_nums.extend(num)
            out_nums.extend(new_out_nums)
        nums = new_nums
            
    print(f"returning {nums} + {out_nums}")
    return nums + out_nums


def process(nums, maps):
    for stage in maps:
        nums = process_stage(nums, stage)
    return nums


if __name__ == "__main__":
    fname = sys.argv[1]
    maps = []
    stage = -1
    lines = [line for line in open(fname, "r")]
    n = [int(x) for x in lines[0].split(":")[1].split()]
    ranges = [range(a,a+b) for (a,b) in list(zip(n[::2], n[1::2]))]
    for line in lines[1:]:
        if ':' in line:
            stage += 1
            maps.append([])
            continue
        if line.strip() == "":
            continue
        dest, src, length = (int(x) for x in line.split())
        maps[stage].append({"r": range(src, src+length), "d": dest})
    outputs = []
    for r in ranges:
        out = process([r], maps)
        print(f"mapped {r} to {out}")
        outputs.append(out)
    # flatten
    outputs = sum(outputs, [])
    print(f"min={min(min(x) for x in outputs)}")

1

u/daggerdragon Dec 06 '23

Your code block is too long for the megathreads. Please edit your post to replace your oversized code with an external link to your code.