34
submitted 11 months ago* (last edited 11 months ago) by Ategon@programming.dev to c/advent_of_code@programming.dev

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)

you are viewing a single comment's thread
view the rest of the comments
[-] capitalpb@programming.dev 2 points 11 months 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: &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(&self, source: &u64) -> u64 {
        let entry = self
            .entries
            .iter()
            .find(|entry| entry.source_range.contains(&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: &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: &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(&self, input: &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(&soil))
            .map(|fertilizer| almanac.fertilizer_to_water.convert(&fertilizer))
            .map(|water| almanac.water_to_light.convert(&water))
            .map(|light| almanac.light_to_temperature.convert(&light))
            .map(|temperature| almanac.temperature_to_humidity.convert(&temperature))
            .map(|humidity| almanac.humidity_to_location.convert(&humidity))
            .min()
            .unwrap()
            .to_string()
    }

    fn star_two(&self, input: &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(&soil))
            .map(|fertilizer| almanac.fertilizer_to_water.convert(&fertilizer))
            .map(|water| almanac.water_to_light.convert(&water))
            .map(|light| almanac.light_to_temperature.convert(&light))
            .map(|temperature| almanac.temperature_to_humidity.convert(&temperature))
            .map(|humidity| almanac.humidity_to_location.convert(&humidity))
            .min()
            .unwrap()
            .to_string()
    }
}
this post was submitted on 05 Dec 2023
34 points (100.0% liked)

Advent Of Code

736 readers
2 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2023

Solution Threads

M T W T F S S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS