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
//! # If You Give A Seed A Fertilizer
use crate::util::iter::*;
use crate::util::parse::*;

pub struct Input {
    seeds: Vec<u64>,
    stages: Vec<Vec<[u64; 3]>>,
}

pub fn parse(input: &str) -> Input {
    let chunks: Vec<_> = input.split("\n\n").collect();
    let seeds = chunks[0].iter_unsigned().collect();
    let stages = chunks[1..]
        .iter()
        .map(|chunk| {
            // Convert from start and length to start and end.
            chunk
                .iter_unsigned()
                .chunk::<3>()
                .map(|[dest, start, length]| [dest, start, start + length])
                .collect()
        })
        .collect();

    Input { seeds, stages }
}

/// Process each seed individually.
pub fn part1(input: &Input) -> u64 {
    let mut seeds = input.seeds.clone();

    for stage in &input.stages {
        for seed in &mut seeds {
            for &[dest, start, end] in stage {
                if start <= *seed && *seed < end {
                    *seed = *seed - start + dest;
                    break;
                }
            }
        }
    }

    *seeds.iter().min().unwrap()
}

/// Process ranges.
pub fn part2(input: &Input) -> u64 {
    let mut current = &mut Vec::new();
    let mut next = &mut Vec::new();
    let next_stage = &mut Vec::new();

    // Convert input pairs to ranges.
    for [start, length] in input.seeds.iter().copied().chunk::<2>() {
        current.push([start, start + length]);
    }

    for stage in &input.stages {
        for &[dest, s2, e2] in stage {
            while let Some([s1, e1]) = current.pop() {
                // Split ranges that overlap into 1, 2 or 3 new ranges.
                // x1 and x2 are the possible overlap.
                let x1 = s1.max(s2);
                let x2 = e1.min(e2);

                if x1 >= x2 {
                    // No overlap.
                    next.push([s1, e1]);
                } else {
                    // Move overlap to new destination. Only compare with next range.
                    next_stage.push([x1 - s2 + dest, x2 - s2 + dest]);

                    // Check remnants with remaining ranges.
                    if s1 < x1 {
                        next.push([s1, x1]);
                    }
                    if x2 < e1 {
                        next.push([x2, e1]);
                    }
                }
            }

            (current, next) = (next, current);
        }

        // Combine elements for the next stage.
        current.append(next_stage);
    }

    current.iter().map(|r| r[0]).min().unwrap()
}