summaryrefslogtreecommitdiffstats
path: root/src/day_05.rs
blob: e9d0b928d944cdb837ad85f42d9ea38967d75814 (plain)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
use std::{ops::Range, str::FromStr};

use crate::{Problem, Solution};

pub struct Day05;

impl Problem for Day05 {
    const DAY: u8 = 5;

    const INPUT: &'static str = include_str!("../input/day_05.txt");
}

impl Solution for Day05 {
    type Answer1 = usize;

    type Answer2 = usize;

    fn part_1(input: &str) -> anyhow::Result<Self::Answer1> {
        let (first, rest) = input
            .trim()
            .split_once('\n')
            .ok_or(anyhow::format_err!("Missing value map label"))?;

        let mut values = first
            .strip_prefix("seeds: ")
            .ok_or(anyhow::format_err!("Failed to get seeds"))?
            .split_whitespace()
            .map(FromStr::from_str)
            .try_collect::<Vec<usize>>()?;

        let value_maps = rest
            .trim()
            .split("\n\n")
            .map(parse_value_maps)
            .try_collect::<Vec<_>>()?;

        for value_map in value_maps {
            values.iter_mut().for_each(|value| {
                if let Some(v) = value_map.iter().find_map(|v| v.map_value(*value)) {
                    *value = v
                }
            })
        }

        values
            .into_iter()
            .min()
            .ok_or(anyhow::format_err!("No values found"))
    }

    fn part_2(input: &str) -> anyhow::Result<Self::Answer2> {
        let (first, rest) = input
            .trim()
            .split_once('\n')
            .ok_or(anyhow::format_err!("Missing value map label"))?;

        let seeds: Vec<Range<usize>> = first
            .strip_prefix("seeds: ")
            .ok_or(anyhow::format_err!("Failed to get seeds"))?
            .split_whitespace()
            .map(FromStr::from_str)
            .try_collect::<Vec<usize>>()?
            .into_iter()
            .array_chunks()
            .map(|[n, len]| Range {
                start: n,
                end: n + len,
            })
            .collect();

        let max = seeds
            .iter()
            .map(|r| r.end)
            .max()
            .ok_or(anyhow::format_err!("Failed to get max seed"))?;

        let value_maps = rest
            .trim()
            .split("\n\n")
            .map(parse_value_maps)
            .try_collect::<Vec<_>>()?;

        (0..=max)
            .find(|location| {
                let mut value = *location;
                for value_map in value_maps.iter().rev() {
                    if let Some(v) = value_map.iter().find_map(|v| v.r_map_value(value)) {
                        value = v;
                    }
                }
                seeds.iter().any(|s| s.contains(&value))
            })
            .ok_or(anyhow::format_err!("Failed to find min seed"))
    }
}

fn parse_value_maps(s: &str) -> anyhow::Result<Vec<ValueMap>> {
    s.trim()
        .lines()
        .skip(1)
        .map(FromStr::from_str)
        .try_collect::<Vec<ValueMap>>()
}

#[derive(Debug, PartialEq, Eq, Hash)]
struct ValueMap {
    source: Range<usize>,
    destination: Range<usize>,
    offset: isize,
}

impl ValueMap {
    fn map_value(&self, value: usize) -> Option<usize> {
        self.source
            .contains(&value)
            .then_some((value as isize + self.offset) as usize)
    }

    fn r_map_value(&self, value: usize) -> Option<usize> {
        self.destination
            .contains(&value)
            .then_some((value as isize - self.offset) as usize)
    }
}

impl FromStr for ValueMap {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut iter = s.trim().splitn(3, ' ').map(FromStr::from_str);

        let (Some(Ok(destination_start)), Some(Ok(source_start)), Some(Ok(length))) =
            (iter.next(), iter.next(), iter.next())
        else {
            anyhow::bail!("Invalid value map range");
        };

        Ok(Self {
            source: source_start..source_start + length,
            destination: destination_start..destination_start + length,
            offset: isize::try_from(destination_start)? - isize::try_from(source_start)?,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const INPUT: &str = indoc::indoc! {"
        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_part_1() -> anyhow::Result<()> {
        Ok(assert_eq!(35, Day05::part_1(INPUT)?))
    }

    #[test]
    fn test_part_2() -> anyhow::Result<()> {
        Ok(assert_eq!(46, Day05::part_2(INPUT)?))
    }
}