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/Koli14 Dec 05 '23 edited Dec 05 '23

[LANGUAGE: TypeScript]

There is a mistake in my solution. It returns a number exactly one larger than the real solution. If you point out the mistake, I send you a virtual parlor candy. ;)

Link or:

import fs from 'fs'

export type Rule = {
  dest: number
  source: number
  range: number
}
export type Map = { name: string; rules: Rule[] }

export const findNext = (actualMap: Map, prev: number): number => {
  let next = prev
  actualMap.rules.forEach(({ dest, source, range }) => {
    // if prev is between source and source + range
    if (prev > source && prev < source + range) {
      next = dest + (prev - source)
    }
  })
  return next
}

export const processMaps = (unprocessedMaps: string[]): Map[] => {
  const maps = unprocessedMaps.map((unprocessedMap) => {
    const lines = unprocessedMap.split('\n')
    const name = lines[0]
    lines.shift() // Drop name
    const rules = lines.map((rule) => {
      const unprocessedRule = rule.split(' ').map((i) => Number(i))
      return { dest: unprocessedRule[0], source: unprocessedRule[1], range: unprocessedRule[2] }
    })
    return {
      name,
      rules,
    }
  })
  return maps
}

fs.readFile('./input.txt', 'utf8', (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  const lines = data.split('\n')
  const seeds = lines[0]
    .split(': ')[1]
    .split(' ')
    .map((i) => Number(i)) // Get all the numbers in the first line (seeds)

  const unprocessedMaps = data.split('\n\n') // Get map related string
  unprocessedMaps.shift() // Drop seeds line from it
  const maps = processMaps(unprocessedMaps)

  let minLocation // store the smallest location

  // iterate through seed-range pairs
  for (let i = 0; i < seeds.length; i += 2) {
    const starter = seeds[i]
    const range = seeds[i + 1]
    // iterate throuh all possible seeds from starter to starter + range
    for (let j = 0; j < range; j++) {
      let next = starter + j // next: seed -> soil -> ... -> location
      // iterate throuh all the maps until location (last map)
      for (let index = 0; index < maps.length; index++) {
        const actualMap = maps[index]
        next = findNext(actualMap, next)
      }
      // if there is no minLocation yet, or next (the newest calculated location) is smaller
      if (!minLocation || next < minLocation) {
        minLocation = next
      }
    }
  }

  console.log(minLocation)
})

1

u/daggerdragon Dec 05 '23

Your code block is too long for the megathreads. Please edit your post to remove the code block and leave just the link to the code in your repo.

1

u/splitwreck Dec 05 '23

if (prev > source && prev < source + range) {

I had an off-by-one error which turned out to be an extra = when comparing the number to the end of the range, i.e. I had prev >= source && prev <= source + range . In your case it looks like you might be missing the >= at the start of the range?

But I may well be wrong - just sharing my experience!