Day 5: If You Give a Seed a Fertilizer


Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots

🔓 Unlocked after 27 mins (current record for time, hard one today)

  • Gobbel2000@feddit.de
    link
    fedilink
    arrow-up
    7
    ·
    edit-2
    1 year ago

    Rust

    Ooof. Part 1 was easy enough, but for part two I initially went with the naive solution of trying every single seed which took more than a minute (I never really measured). Although that got me the right answer, to me that was just unacceptable.

    I proceeded to try and combine all mappings into one but gave up after spending way too much time on it.

    Then I had the idea that the lowest number in the end must lie at the beginning of a range somewhere. Either the start of a seed range in the beginning or the start of a range in one of the mappings. Any in-between numbers must end up with a higher result. So I considered the start points of all ranges, went through the mappings in reverse to find out if that point is actually within a seed range, and only tested those starting points.

    Finally I had only 183 points to test which ran much faster (0.9ms).

    • bamboo@lemmy.blahaj.zone
      link
      fedilink
      English
      arrow-up
      3
      ·
      1 year ago

      Then I had the idea that the lowest number in the end must lie at the beginning of a range somewhere. Either the start of a seed range in the beginning or the start of a range in one of the mappings.

      This really helped me out. I was stuck on either trying every single seed, or working backwards and trying every single location from 0 to infinity, and couldn’t wrap my head around how to filter down the list to be manageable. Your comment made it all make sense.

      In the end, was able to work backwards with the 172 lowest locations in each range to get potential seeds, and from there was able to get a short list of 89 valid seeds (including the original seed values) to then figure out which one has the shortest location.

      Thanks!

    • Treeniks@lemmy.ml
      link
      fedilink
      English
      arrow-up
      1
      ·
      edit-2
      1 year ago

      I’m a little confused about this one. The mappings are total, that is any number that is not defined explicitly gets mapped to itself. So it’s easy to create an example where the lowest number does not get mentioned within a range:

      seeds: 0 3
      
      seed-to-soil map:
      10 0 2
      
      soil-to-fertilizer map:
      100 200 5
      
      fertilizer-to-water map:
      100 200 5
      
      water-to-light map:
      100 200 5
      
      light-to-temperature map:
      100 200 5
      
      temperature-to-humidity map:
      100 200 5
      
      humidity-to-location map:
      100 200 5
      

      Here, we have seeds 0, 1 and 2. seed 0 gets mapped to location 10, seed 1 gets mapped to location 11 and seed 2 gets mapped to location 2. That means location 2 would be the answer, but it’s not a start of any range. I guess this just doesn’t happen in any of the inputs?

      EDIT: actually it’s double weird. If you implemented a backwards search, that is you create reverse mappings and then try out all locations (which is what I and many others did), the result of the above example is location 0, whereas if you create a forwards brute force of all seeds, the result is 2. For the reverse approach to work in all cases, the mappings would have to be bijective.

      • Gobbel2000@feddit.de
        link
        fedilink
        arrow-up
        1
        ·
        1 year ago

        Indeed, my solution fails on this input (returns 10, which is the location to seed 0), but it can be easily solved by also adding the ends of each range as well.

        Maybe the input was quite forgiving. Thinking about it more, reversing the mapping can get quite involved, because it is neither surjective nor injective, so the inverse can actually have any number of results.

        In your example there is no input that maps to 0, but there are two inputs that map to 11 (1 and 11). If the seed-to-soil map also included 10 20 2, 21 would also map to 11.

  • Ategon@programming.devOPM
    link
    fedilink
    arrow-up
    5
    ·
    edit-2
    1 year ago

    [JavaScript] Well that was by far the hardest out of all of the days, part 1 was relatively fine but part 2 took me awhile of trying different things

    Ended up solving it by working backwards by trying different location values and seeing if that can become a valid seed. Takes around 3 secs to compute the answer.

    Link to code

    Part 1 Code Block
    // Part 1
    // ======
    
    function part1(input) {
      const split = input.split("\r\n\r\n");
    
      let pastValues = split[0].match(/\d+/g).map((x) => parseInt(x));
      let currentValues = [];
    
      for (const section of split.slice(1)) {
        for (const line of section.split("\r\n")) {
          const values = line.match(/\d+/g)?.map((x) => parseInt(x));
    
          if (!values) {
            continue;
          }
    
          const sourceStart = values[1];
          const destinationStart = values[0];
          const length = values[2];
    
          for (let i = 0; i < pastValues.length; i++) {
            if (
              pastValues[i] >= sourceStart &&
              pastValues[i] < sourceStart + length
            ) {
              currentValues.push(destinationStart + pastValues[i] - sourceStart);
              pastValues.splice(i, 1);
              i--;
            }
          }
        }
    
        for (let i = 0; i < pastValues.length; i++) {
          currentValues.push(pastValues[i]);
        }
    
        pastValues = [...currentValues];
        currentValues = [];
      }
    
      return Math.min(...pastValues);
    }
    
    Part 2 Code Block
    // Part 2
    // ======
    
    function part2(input) {
      const split = input.split("\r\n\r\n");
    
      let seeds = split[0].match(/\d+/g).map((x) => parseInt(x));
      seeds = seeds
        .filter((x, i) => i % 2 == 0)
        .map((x, i) => [x, seeds[i * 2 + 1]]);
    
      const maps = split
        .slice(1)
        .map((x) => {
          const lines = x.split("\r\n");
          return lines
            .map((x) => x.match(/\d+/g)?.map((x) => parseInt(x)))
            .filter((x) => x);
        })
        .reverse();
    
      for (let i = 0; true; i++) {
        let curValue = i;
    
        for (const map of maps) {
          for (const line of map) {
            const sourceStart = line[1];
            const destinationStart = line[0];
            const length = line[2];
    
            if (
              curValue >= destinationStart &&
              curValue < destinationStart + length
            ) {
              curValue = sourceStart + curValue - destinationStart;
              break;
            }
          }
        }
    
        for (const [seedRangeStart, seedRangeLength] of seeds) {
          if (
            curValue >= seedRangeStart &&
            curValue < seedRangeStart + seedRangeLength
          ) {
            return i;
          }
        }
      }
    }
    
    • cacheson@kbin.social
      link
      fedilink
      arrow-up
      1
      ·
      1 year ago

      Ended up solving it by working backwards by trying different location values and seeing if that can become a valid seed.

      Huh, that’s clever.

      • Ategon@programming.devOPM
        link
        fedilink
        arrow-up
        1
        ·
        1 year ago

        Turns out I got really lucky and my location value is much lower than most peoples which is why it can be solved relatively quickly

    • Leo Uino@lemmy.sdf.org
      link
      fedilink
      arrow-up
      1
      ·
      1 year ago

      Torn between doing the problem backwards and implementing a more general case – glad to know both approaches work out in the end!

  • kartoffelsaft@programming.dev
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    1 year ago

    Odin

    When I read the problem description I expected the input to also be 2 digit numbers. When I looked at it I just had to say “huh.”

    Second part I think you definitely have to do in reverse (edit: if you are doing a linear search for the answer), as that allows you to nope out as soon as you find a match, whereas with doing it forward you have to keep checking just in case.

    Formatted code

    package day5
    
    import "core:fmt"
    import "core:strings"
    import "core:slice"
    import "core:strconv"
    
    Range :: struct {
        dest: int,
        src: int,
        range: int,
    }
    
    Mapper :: struct {
        ranges: []Range,
    }
    
    parse_range :: proc(s: string) -> (ret: Range) {
        rest := s
    
        parseLen := -1
    
        destOk: bool
        ret.dest, destOk = strconv.parse_int(rest, 10, &parseLen)
        rest = strings.trim_left_space(rest[parseLen:])
    
        srcOk: bool
        ret.src, srcOk = strconv.parse_int(rest, 10, &parseLen)
        rest = strings.trim_left_space(rest[parseLen:])
    
        rangeOk: bool
        ret.range, rangeOk = strconv.parse_int(rest, 10, &parseLen)
    
        return
    }
    
    parse_mapper :: proc(ss: []string) -> (ret: Mapper) {
        ret.ranges = make([]Range, len(ss)-1)
        for s, i in ss[1:] {
            ret.ranges[i] = parse_range(s)
        }
    
        return
    }
    
    parse_mappers :: proc(ss: []string) -> []Mapper {
        mapsStr := make([dynamic][]string)
        defer delete(mapsStr)
    
        restOfLines := ss
        isLineEmpty :: proc(s: string)->bool {return len(s)==0}
    
        for i, found := slice.linear_search_proc(restOfLines, isLineEmpty); 
            found; 
            i, found  = slice.linear_search_proc(restOfLines, isLineEmpty) {
            
            append(&mapsStr, restOfLines[:i])
            restOfLines = restOfLines[i+1:]
        }
        append(&mapsStr, restOfLines[:])
    
        return slice.mapper(mapsStr[1:], parse_mapper)
    }
    
    apply_mapper :: proc(mapper: Mapper, num: int) -> int {
        for r in mapper.ranges {
            if num >= r.src && num - r.src < r.range do return num - r.src + r.dest
        }
    
        return num
    }
    
    p1 :: proc(input: []string) {
        maps := parse_mappers(input)
        defer {
            for m in maps do delete(m.ranges)
            delete(maps)
        }
    
        restSeeds := input[0][len("seeds: "):]
        min := 0x7fffffff
    
        for len(restSeeds) > 0 {
            seedLen := -1
            seed, seedOk := strconv.parse_int(restSeeds, 10, &seedLen)
            restSeeds = strings.trim_left_space(restSeeds[seedLen:])
    
            fmt.print(seed)
            for m in maps {
                seed = apply_mapper(m, seed)
                fmt.print(" ->", seed)
            }
            fmt.println()
    
            if seed < min do min = seed
        }
    
        fmt.println(min)
    }
    
    apply_mapper_reverse :: proc(mapper: Mapper, num: int) -> int {
        for r in mapper.ranges {
            if num >= r.dest && num - r.dest < r.range do return num - r.dest + r.src
        }
    
        return num
    }
    
    p2 :: proc(input: []string) {
        SeedRange :: struct {
            start: int,
            len: int,
        }
    
        seeds := make([dynamic]SeedRange)
        restSeeds := input[0][len("seeds: "):]
    
        for len(restSeeds) > 0 {
            seedLen := -1
            seedS, seedSOk := strconv.parse_int(restSeeds, 10, &seedLen)
            restSeeds = strings.trim_left_space(restSeeds[seedLen:])
    
            seedL, seedLOk := strconv.parse_int(restSeeds, 10, &seedLen)
            restSeeds = strings.trim_left_space(restSeeds[seedLen:])
    
            append(&seeds, SeedRange{seedS, seedL})
        }
    
        maps := parse_mappers(input)
        defer {
            for m in maps do delete(m.ranges)
            delete(maps)
        }
    
        for i := 0; true; i += 1 {
            rseed := i
            #reverse for m in maps {
                rseed = apply_mapper_reverse(m, rseed)
            }
    
            found := false
            for sr in seeds {
                if rseed >= sr.start && rseed < sr.start + sr.len {
                    found = true
                    break
                }
            }
            if found {
                fmt.println(i)
                break
            }
        }
    }
    
  • Leo Uino@lemmy.sdf.org
    link
    fedilink
    arrow-up
    4
    ·
    1 year ago

    Haskell

    Not hugely proud of this one; part one would have been easier if I’d spend more time reading the question and not started on an overly-general solution, and I lost a lot of time on part two to a missing a +. More haste, less speed, eh?

    import Data.List
    import Data.List.Split
    
    readInput :: String -> ([Int], [(String, [(Int, Int, Int)])])
    readInput s =
      let (seedsChunk : mapChunks) = splitOn [""] $ lines s
          seeds = map read $ tail $ words $ head seedsChunk
          maps = map readMapChunk mapChunks
       in (seeds, maps)
      where
        readMapChunk (title : rows) =
          let name = head $ words title
              entries = map ((\[a, b, c] -> (a, b, c)) . map read . words) rows
           in (name, entries)
    
    part1 (seeds, maps) =
      let f = foldl1' (flip (.)) $ map (ref . snd) maps
       in minimum $ map f seeds
      where
        ref [] x = x
        ref ((a, b, c) : rest) x =
          let i = x - b
           in if i >= 0 && i < c
                then a + i
                else ref rest x
    
    mapRange :: [(Int, Int, Int)] -> (Int, Int) -> [(Int, Int)]
    mapRange entries (start, end) =
      go start $ sortOn (\(_, b, _) -> b) entries
      where
        go i [] = [(i, end)]
        go i es@((a, b, c) : rest)
          | i > end = []
          | b > end = go i []
          | b + c <= i = go i rest
          | i < b = (i, b - 1) : go b es
          | otherwise =
              let d = min (b + c - 1) end
               in (a + i - b, a + d - b) : go (d + 1) rest
    
    part2 (seeds, maps) =
      let seedRanges = map (\[a, b] -> (a, a + b - 1)) $ chunksOf 2 seeds
       in minimum $ map fst $ foldl' (flip mapRanges) seedRanges $ map snd maps
      where
        mapRanges m = concatMap (mapRange m)
    
    main = do
      input <- readInput <$> readFile "input05"
      print $ part1 input
      print $ part2 input
    
  • purplemonkeymad@programming.dev
    link
    fedilink
    arrow-up
    4
    ·
    1 year ago

    Finally. :cries:

    Part 1 was fine, I was figuring I might be able to practice classes.

    Part 2 told me that nope, memory management required for you. In the end instead of calculating seeds, I resolved the whole thing down to a single mapping of seeds to locations. Then I could just sort by location ranges and try to see if they were a seed. Code is full of old parts from failed solutions but I’ve had enough of day 5, so I no longer care to clean it up.

  • bugsmith@programming.dev
    link
    fedilink
    arrow-up
    3
    ·
    edit-2
    1 year ago

    Like many others, I really didn’t enjoy this one. I particularly struggled with part 02, which ended up with me just brute forcing it and checking each seed. On my system it took over 15 minutes to run, which is truly awful. I’m open to pointers on how I could better have solved part two.

    Solution in Rust 🦀

    Formatted Solution on GitLab

    Code
    use std::{
        env, fs,
        io::{self, BufReader, Read},
    };
    
    fn main() -> io::Result<()> {
        let args: Vec = env::args().collect();
        let filename = &args[1];
        let file1 = fs::File::open(filename)?;
        let file2 = fs::File::open(filename)?;
        let mut reader1 = BufReader::new(file1);
        let mut reader2 = BufReader::new(file2);
    
        println!("Part one: {}", process_part_one(&mut reader1));
        println!("Part two: {}", process_part_two(&mut reader2));
        Ok(())
    }
    
    #[derive(Debug)]
    struct Map {
        lines: Vec,
    }
    
    impl Map {
        fn map_to_lines(&self, key: u32) -> u32 {
            for line in &self.lines {
                if line.in_range(key) {
                    return line.map(key);
                }
            }
            key
        }
    }
    
    #[derive(Debug)]
    struct MapLine {
        dest_range: u32,
        source_range: u32,
        range_length: u32,
    }
    
    impl MapLine {
        fn map(&self, key: u32) -> u32 {
            let diff = key - self.source_range;
            if self.dest_range as i64 + diff as i64 > 0 {
                return (self.dest_range as i64 + diff as i64) as u32;
            }
            key
        }
    
        fn in_range(&self, key: u32) -> bool {
            self.source_range <= key
                && (key as i64) < self.source_range as i64 + self.range_length as i64
        }
    }
    
    fn parse_input(reader: &amp;mut BufReader) -> (Vec, Vec<map>) {
        let mut almanac = String::new();
        reader
            .read_to_string(&amp;mut almanac)
            .expect("read successful");
        let parts: Vec&lt;&amp;str> = almanac.split("\n\n").collect();
        let (seeds, others) = parts.split_first().expect("at least one part");
        let seeds: Vec&lt;_> = seeds
            .split(": ")
            .last()
            .expect("at least one")
            .split_whitespace()
            .map(|s| s.to_string())
            .collect();
        let maps: Vec&lt;_> = others
            .iter()
            .map(|item| {
                let lines_iter = item
                    .split(':')
                    .last()
                    .expect("exists")
                    .trim()
                    .split('\n')
                    .map(|nums| {
                        let nums_split = nums.split_whitespace().collect::>();
                        MapLine {
                            dest_range: nums_split[0].parse().expect("is digit"),
                            source_range: nums_split[1].parse().expect("is digit"),
                            range_length: nums_split[2].parse().expect("is digit"),
                        }
                    });
                Map {
                    lines: lines_iter.collect(),
                }
            })
            .collect();
        (seeds, maps)
    }
    
    fn process_part_one(reader: &amp;mut BufReader) -> u32 {
        let (seeds, maps) = parse_input(reader);
        let mut res = u32::MAX;
        for seed in &amp;seeds {
            let mut val = seed.parse::().expect("is digits");
            for map in &amp;maps {
                val = map.map_to_lines(val);
            }
            res = u32::min(res, val);
        }
        res
    }
    
    fn process_part_two(reader: &amp;mut BufReader) -> u32 {
        let (seeds, maps) = parse_input(reader);
        let seed_chunks: Vec&lt;_> = seeds.chunks(2).collect();
        let mut res = u32::MAX;
        for chunk in seed_chunks {
            let range_start: u32 = chunk[0].parse().expect("is digits");
            let range_length: u32 = chunk[1].parse().expect("is digits");
            let range_end: u32 = range_start + range_length;
            for seed in range_start..range_end {
                let mut val = seed;
                for map in &amp;maps {
                    val = map.map_to_lines(val);
                }
                res = u32::min(res, val);
            }
        }
        res
    }
    
    #[cfg(test)]
    mod tests {
        use super::*;
    
        const INPUT: &amp;str = "seeds: 79 14 55 13
    
    seed-to-soil map:
    50 98 2
    52 50 48
    
    soil-to-fertilizer map:
    0 15 37
    37 52 2
    39 0 15
    
    fertilizer-to-water map:
    49 53 8
    0 11 42
    42 0 7
    57 7 4
    
    water-to-light map:
    88 18 7
    18 25 70
    
    light-to-temperature map:
    45 77 23
    81 45 19
    68 64 13
    
    temperature-to-humidity map:
    0 69 1
    1 0 69
    
    humidity-to-location map:
    60 56 37
    56 93 4";
    
        #[test]
        fn test_process_part_one() {
            let input_bytes = INPUT.as_bytes();
            assert_eq!(35, process_part_one(&amp;mut BufReader::new(input_bytes)));
        }
    
        #[test]
        fn test_process_part_two() {
            let input_bytes = INPUT.as_bytes();
            assert_eq!(46, process_part_two(&amp;mut BufReader::new(input_bytes)));
        }
    }
    

    :::</map>

    • bamboo@lemmy.blahaj.zone
      link
      fedilink
      English
      arrow-up
      5
      ·
      1 year ago

      I got far enough to realize that you probably needed to work backwards and given a location, determine the accompanying seed, and then check if that seed is one of the ones listed in the range. Still though, starting at 0 for location and working up was taking forever to find the first valid seed

      Someone in this thread pointed out that if you picked the first value of each range in the map, working backwards from those points will get you a short list of seeds which map to low values. You then check if those seeds are valid, and also check the location of the first seeds in the range (the rest of the seeds in the range don’t matter because those are covered by the first check). This ends up with about 200 locations which you can sort, to get the lowest value.

      • walter_wiggles@lemmy.nz
        link
        fedilink
        arrow-up
        3
        ·
        1 year ago

        I tried brute forcing it but couldn’t get the process to finish. Iterating through hundreds of millions of seeds is no bueno.

        After reading your comment though I got the idea to map whole seed ranges instead of individual seeds. That finished in no time of course.

  • cvttsd2si@programming.dev
    link
    fedilink
    arrow-up
    3
    ·
    1 year ago

    Scala3

    kind of convoluted, but purely functional

    import scala.collection.immutable.NumericRange.Exclusive
    import math.max
    import math.min
    
    extension [A] (l: List[A])
      def chunk(pred: A => Boolean): List[List[A]] =
        def go(l: List[A], partial_acc: List[A], acc: List[List[A]]): List[List[A]] =
          l match
            case (h :: t) if pred(h) => go(t, List(), partial_acc.reverse :: acc)
            case (h :: t) => go(t, h :: partial_acc, acc)
            case _ => partial_acc.reverse :: acc
        
        go(l, List(), List()).reverse
    
    type R = Exclusive[Long]
    
    def intersectTranslate(r: R, c: R, t: Long): R =
        (t + max(r.start, c.start) - c.start) until (t + min(r.end, c.end) - c.start)
    
    case class MappingEntry(from: R, to: Long)
    case class Mapping(entries: List[MappingEntry], produces: String):
        def resolveRange(in: R): List[R] =
            entries.map(e => intersectTranslate(in, e.from, e.to)).filter(!_.isEmpty)
    
    def completeEntries(a: List[MappingEntry]): List[MappingEntry] = 
        a ++ ((0L until 0L) +: a.map(_.from).sorted :+ (Long.MaxValue until Long.MaxValue)).sliding(2).flatMap{ case List(a, b) => Some(MappingEntry(a.end until b.start, a.end)); case _ => None}.toList
    
    def parse(a: List[String], init: List[Long] => List[R]): (List[R], Map[String, Mapping]) =
        def parseEntry(s: String): MappingEntry =
            s match
                case s"$end $start $range" => MappingEntry(start.toLong until start.toLong + range.toLong, end.toLong)
    
        a.chunk(_ == "") match
            case List(s"seeds: $seeds") :: maps => 
                init(seeds.split(raw"\s+").map(_.toLong).toList) -> (maps.flatMap{ case s"$from-to-$to map:" :: entries => Some(from -> Mapping(completeEntries(entries.map(parseEntry)), to)); case _ => None }).toMap
            case _ => (List(), Map()).ensuring(false)
    
    def singletons(a: List[Long]): List[R] = a.map(s => s until s + 1)
    def paired(a: List[Long]): List[R] = a.grouped(2).flatMap{ case List(x, y) => Some(x until x+y); case _ => None }.toList
    
    def chase(d: (List[R], Map[String, Mapping]), initial: String, target: String) =
        val (init, m) = d
        def go(a: List[R], s: String): List[R] =
            if trace(s) == target then a else
                val x = m(s)
                go(a.flatMap(x.resolveRange), x.produces)
        go(trace(init), initial)
    
    def task1(a: List[String]): Long = 
        chase(parse(a, singletons), "seed", "location").min.start
    
    def task2(a: List[String]): Long =
        chase(parse(a, paired), "seed", "location").min.start
    
  • perviouslyiner@lemm.ee
    link
    fedilink
    English
    arrow-up
    3
    ·
    edit-2
    1 year ago

    This was interesting! So iterating through the solution space would be infeasible here and it seems we need to look for boundaries between regions and follow them to find places where a solution could occur.

    Python: https://pastebin.com/8Ckx36fu

    • Make a list of places where location mappings are discontinuous (0, the end of each mapping, and the number before)
    • Repeat this for discontinuities in each intermediate layer
    • Trace each such location to its seed, and filter by seed ranges
    • Run the very minimal set of interesting seed numbers (around 2000 seeds) through the existing part1 algorithm
  • cacheson@kbin.social
    link
    fedilink
    arrow-up
    3
    ·
    1 year ago

    Nim

    Woof. Part 1 was simple enough. I thought I could adapt my solution to part 2 pretty easily, just add all the values in the ranges to the starting set. Worked fine for the example, but the ranges for the actual input are too large. Ended up taking 16gb of RAM and crunching forever.

    I finally abandoned my quick and dirty approach when rewriting part 2, and made some proper types and functions. Treated each range as an object, and used set operations on them. The difference operation tends to fragment the range that it’s used on, so I meant to write some code to defragment the ranges after each round of mappings. Forgot to do so, but the code ran quick enough this time anyway.

    • janAkali@lemmy.one
      link
      fedilink
      English
      arrow-up
      1
      ·
      1 year ago

      Treated each range as an object, and used set operations on them

      That’s smart. Honestly, I don’t understand how it works. 😅

      The difference operation tends to fragment the range that it’s used on, so I meant to write some code to defragment the ranges after each round of mappings. Forgot to do so, but the code ran quick enough this time anyway.

      I’ve got different solution from yours, but this part is the same, lol. My code slices the ranges into 1-3 parts on each step, so I also planned to ‘defragment’ them. But performance is plenty without this step, ~450 microseconds for both parts on my PC.

      • cacheson@kbin.social
        link
        fedilink
        arrow-up
        2
        ·
        1 year ago

        Treated each range as an object, and used set operations on them

        That’s smart. Honestly, I don’t understand how it works. 😅

        “Set operations” should probably be in quotes. I just mean that I implemented the * (intersection) and - (difference) operators for my ValueRange type. The intersection operator works like it does for sets, just returning the overlap. The difference operator has to work a little differently, because ranges have to be contiguous, whereas sets don’t, so it returns a sequence of ValueRange objects.

        My ValueMapping type uses a ValueRange for it’s source, so applying it to a range just involves using the intersection operator to determine what part of the range needs to move, and the difference operator to determine which parts are left.

        • janAkali@lemmy.one
          link
          fedilink
          English
          arrow-up
          1
          ·
          edit-2
          1 year ago

          Well, then we have the same solution but coded very differently. Here’s mine.

          ruleApplied is one function with almost all logic. I take a range and compare it to a rule’s source range (50 98 2 is a rule). Overlaps get transformed and collected into the first sequence and everything that left goes in the second. I need two seqs there, for transformed values to skip next rules in the same map.

          Repeat for each rule and each map (seq[Rule]). And presto, it’s working!

          • cacheson@kbin.social
            link
            fedilink
            arrow-up
            2
            ·
            1 year ago

            Yeah, roughly the same idea. I guess I could have just used HSlice for my range type, I thought maybe there was some special magic to it.

            It looks like your if-else ladder misses a corner case, where one range only intersects with the first or last element of the other. Switching to &lt;= and >= for those should take care of it though.

  • janAkali@lemmy.one
    link
    fedilink
    English
    arrow-up
    2
    ·
    edit-2
    1 year ago

    Nim

    Part 1 was really easy.
    Part 2, I struggled to solve efficiently, so I just ran naive bruteforce for 5 minutes until I got the answer.
    Later, I’ve rewritten my solution for Part 2. The idea is to handle ranges as ranges, check seed ranges against map ranges, transform overlaps, but keep not-overlapping parts.

    Total runtime after rewrite: ~ 0.4 ms.
    Today’s puzzle was nice - 8.5/10.

    Code: day_05/solution.nim

  • sjmulder@lemmy.sdf.org
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    1 year ago

    [C]

    My first approach to part 2 was to take the list of ranges, map it to a new list of (possibly split up) ranges, etc, but I realized that would take more memory and bookkeeping than I’d like. Scrapped it and rewrote it with recursion. Much cleaner and the benchmarks are still looking good! (But for how much longer?)

    $ bmake bench
    day01  0:00.00  1380 Kb  0+78 faults
    day02  0:00.00  1660 Kb  0+82 faults
    day03  0:00.00  1540 Kb  0+107 faults
    day04  0:00.00  1536 Kb  0+80 faults
    day05  0:00.00  1668 Kb  0+83 faults
    

    https://github.com/sjmulder/aoc/blob/master/2023/c/day05.c

    Edit: I see some people went for looping from 0 to try possible answers. Clever and short but I wanted to go for a more efficient approach.

    • iAvicenna@lemmy.world
      link
      fedilink
      arrow-up
      1
      ·
      1 year ago

      Started 4 days late so coming up from behind. Day 5 was the first solution I am somewhat proud of. I used interval arithmetics. I had to somewhat extend a class interval from pyinterval into something I called PointedInterval. In the end part 2 was completed in 0.32 seconds. It does not reverse engineer the solution starting from 0 location and inverse mapping until you find a seed (that was how I was initially planning to do it). It maps forward everything as intervals. There is a bit of a boiler plate which is in the utils file.

  • capitalpb@programming.dev
    link
    fedilink
    English
    arrow-up
    2
    ·
    1 year ago

    Well, I can’t say much about this one. The code is ugly, horribly inefficient, and part two takes a solid half hour to run. It got the right answer though, so that’s something I suppose. I think something like nom to parse the input would be much cleaner, and there’s got to be a better way of going about part two than just brute forcing through every possible seed, but hey, it works so that’s good enough for now.

    https://github.com/capitalpb/advent_of_code_2023/blob/main/src/solvers/day05.rs

    #[derive(Clone, Debug)]
    struct AlmanacMapEntry {
        destination_range: RangeInclusive,
        source_range: RangeInclusive,
    }
    
    #[derive(Clone, Debug)]
    struct AlmanacMap {
        entries: Vec,
    }
    
    impl AlmanacMap {
        fn from(input: &amp;str) -> AlmanacMap {
            let entries = input
                .lines()
                .skip(1)
                .map(|line| {
                    let numbers = line
                        .split(' ')
                        .filter_map(|number| number.parse::().ok())
                        .collect::>();
                    AlmanacMapEntry {
                        destination_range: numbers[0]..=(numbers[0] + numbers[2]),
                        source_range: numbers[1]..=(numbers[1] + numbers[2]),
                    }
                })
                .collect();
            AlmanacMap { entries }
        }
    
        fn convert(&amp;self, source: &amp;u64) -> u64 {
            let entry = self
                .entries
                .iter()
                .find(|entry| entry.source_range.contains(&amp;source));
    
            if let Some(entry) = entry {
                entry.destination_range.start() + (source - entry.source_range.start())
            } else {
                source.clone()
            }
        }
    }
    
    #[derive(Debug)]
    struct Almanac {
        seeds: Vec,
        seed_to_soil: AlmanacMap,
        soil_to_fertilizer: AlmanacMap,
        fertilizer_to_water: AlmanacMap,
        water_to_light: AlmanacMap,
        light_to_temperature: AlmanacMap,
        temperature_to_humidity: AlmanacMap,
        humidity_to_location: AlmanacMap,
    }
    
    impl Almanac {
        fn star_one_from(input: &amp;str) -> Almanac {
            let mut input_sections = input
                .split("\n\n")
                .map(|section| section.split_once(':').unwrap().1);
    
            let seeds = input_sections
                .next()
                .unwrap()
                .split_whitespace()
                .filter_map(|seed| seed.parse::().ok())
                .collect();
    
            let almanac_maps = input_sections.map(AlmanacMap::from).collect::>();
    
            Almanac {
                seeds,
                seed_to_soil: almanac_maps[0].clone(),
                soil_to_fertilizer: almanac_maps[1].clone(),
                fertilizer_to_water: almanac_maps[2].clone(),
                water_to_light: almanac_maps[3].clone(),
                light_to_temperature: almanac_maps[4].clone(),
                temperature_to_humidity: almanac_maps[5].clone(),
                humidity_to_location: almanac_maps[6].clone(),
            }
        }
    
        fn star_two_from(input: &amp;str) -> Almanac {
            let mut input_sections = input
                .split("\n\n")
                .map(|section| section.split_once(':').unwrap().1);
    
            let seeds = input_sections
                .next()
                .unwrap()
                .split_whitespace()
                .filter_map(|seed| seed.parse::().ok())
                .collect::>()
                .chunks(2)
                .map(|chunk| (chunk[0]..(chunk[0] + chunk[1])).collect::>())
                .flatten()
                .collect::>();
    
            let almanac_maps = input_sections.map(AlmanacMap::from).collect::>();
    
            Almanac {
                seeds,
                seed_to_soil: almanac_maps[0].clone(),
                soil_to_fertilizer: almanac_maps[1].clone(),
                fertilizer_to_water: almanac_maps[2].clone(),
                water_to_light: almanac_maps[3].clone(),
                light_to_temperature: almanac_maps[4].clone(),
                temperature_to_humidity: almanac_maps[5].clone(),
                humidity_to_location: almanac_maps[6].clone(),
            }
        }
    }
    
    pub struct Day05;
    
    impl Solver for Day05 {
        fn star_one(&amp;self, input: &amp;str) -> String {
            let almanac = Almanac::star_one_from(input);
    
            almanac
                .seeds
                .iter()
                .map(|seed| almanac.seed_to_soil.convert(seed))
                .map(|soil| almanac.soil_to_fertilizer.convert(&amp;soil))
                .map(|fertilizer| almanac.fertilizer_to_water.convert(&amp;fertilizer))
                .map(|water| almanac.water_to_light.convert(&amp;water))
                .map(|light| almanac.light_to_temperature.convert(&amp;light))
                .map(|temperature| almanac.temperature_to_humidity.convert(&amp;temperature))
                .map(|humidity| almanac.humidity_to_location.convert(&amp;humidity))
                .min()
                .unwrap()
                .to_string()
        }
    
        fn star_two(&amp;self, input: &amp;str) -> String {
            let almanac = Almanac::star_two_from(input);
    
            almanac
                .seeds
                .iter()
                .map(|seed| almanac.seed_to_soil.convert(seed))
                .map(|soil| almanac.soil_to_fertilizer.convert(&amp;soil))
                .map(|fertilizer| almanac.fertilizer_to_water.convert(&amp;fertilizer))
                .map(|water| almanac.water_to_light.convert(&amp;water))
                .map(|light| almanac.light_to_temperature.convert(&amp;light))
                .map(|temperature| almanac.temperature_to_humidity.convert(&amp;temperature))
                .map(|humidity| almanac.humidity_to_location.convert(&amp;humidity))
                .min()
                .unwrap()
                .to_string()
        }
    }