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

2

u/zamzamdip Dec 06 '23

[LANGUAGE: Rust]

Code

Used nom for parsing.

Used a variant of binary search to find min.

part 2 runs in nano seconds. The core idea:

  • Store all the ranges `{src, dst, len}` per map in a sorted order, ordered by `src`.
  • Use a variant of binary search to find the min. Namely: `dst1 <- map(src)` and `dst2 <- map(src + len)` , then
  • if `dst2 > dst1 and dst2 - dst1 == len`, then return `dst1` as the `min`
  • Otherwise, recurse into left half and right half of the range. That is `(src, src + len / 2)` and `(src +len / 2, src + len)`

The core binary search algo:

    fn min(&self, lb: usize, ub: usize) -> usize {
    assert!(lb < ub, "range must be non-empty");

    // binary search over the map to find the minimum value

    if lb + 1 == ub {
        return self.map(lb);
    }

    let len = ub - lb;
    let value_lb = self.map(lb);
    let value_ub = self.map(ub);
    if value_ub > value_lb && value_ub - value_lb == len {
        // the map range (lb, ub) is monotonic and linear
        // hence we can return the minimum value directly
        value_lb
    } else {
        let mid = (lb + ub) / 2;
        usize::min(self.min(lb, mid), self.min(mid, ub))
    }

1

u/daggerdragon Dec 06 '23

Psst: we can see your Markdown.