summaryrefslogtreecommitdiffstats
path: root/src/bin/2022/day5.rs
blob: b09e2e03ce8d0d929fbfea32a795ecf536274bf2 (plain) (blame)
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
#![allow(dead_code)]
#![allow(unused_variables)]

use advent_of_code::prelude::*;

#[derive(Default)]
pub struct Pile(Vec<char>);

impl Pile {
    fn move_from(&mut self, other: &mut Self, n: usize) {
        for _ in 0..n {
            self.0.push(other.0.pop().unwrap());
        }
    }

    fn unshift(&mut self, c: char) {
        self.0.insert(0, c);
    }

    fn push(&mut self, c: char) {
        self.0.push(c);
    }

    fn pop(&mut self) -> Option<char> {
        self.0.pop()
    }

    fn top(&self) -> Option<char> {
        self.0.last().copied()
    }
}

struct Instruction {
    count: usize,
    from: usize,
    to: usize,
}

pub struct Crates {
    piles: Vec<Pile>,
    instructions: Vec<Instruction>,
}

pub fn parse(fh: File) -> Result<Crates> {
    let mut lines = parse::raw_lines(fh);
    let mut piles: Vec<Pile> = vec![];

    for line in lines.by_ref() {
        if line.starts_with(" 1 ") {
            break;
        }

        let pile_count = (line.len() + 1) / 4;
        piles.resize_with(pile_count, Default::default);

        for (pile_idx, pile) in piles.iter_mut().enumerate() {
            let idx = pile_idx * 4;
            assert!([' ', '['].contains(&line.chars().nth(idx).unwrap()));
            let crate_name = line.chars().nth(idx + 1).unwrap();
            if crate_name != ' ' {
                pile.unshift(crate_name);
            }
            assert!([' ', ']'].contains(&line.chars().nth(idx + 2).unwrap()));
            assert!([Some(' '), None].contains(&line.chars().nth(idx + 3)));
        }
    }

    assert_eq!(lines.next().unwrap(), "");

    let mut instructions = vec![];
    for line in lines {
        let captures = regex_captures!(
            r"^move ([0-9]+) from ([0-9]+) to ([0-9]+)$",
            &line
        )
        .unwrap();
        let count = captures[1].parse().unwrap();
        let from = captures[2].parse().unwrap();
        let to = captures[3].parse().unwrap();
        instructions.push(Instruction { count, from, to });
    }

    Ok(Crates {
        piles,
        instructions,
    })
}

pub fn part1(mut crates: Crates) -> Result<String> {
    for Instruction { count, from, to } in crates.instructions {
        for _ in 0..count {
            let c = crates.piles[from - 1].pop().unwrap();
            crates.piles[to - 1].push(c);
        }
    }
    Ok(crates
        .piles
        .iter()
        .map(|pile| pile.top().unwrap())
        .collect())
}

pub fn part2(mut crates: Crates) -> Result<String> {
    for Instruction { count, from, to } in crates.instructions {
        let mut tmp = vec![];
        for _ in 0..count {
            let c = crates.piles[from - 1].pop().unwrap();
            tmp.push(c);
        }
        for c in tmp.iter().copied().rev() {
            crates.piles[to - 1].push(c);
        }
    }
    Ok(crates
        .piles
        .iter()
        .map(|pile| pile.top().unwrap())
        .collect())
}

#[test]
fn test() {
    assert_eq!(
        part1(parse(parse::data(2022, 5).unwrap()).unwrap()).unwrap(),
        "PSNRGBTFT"
    );
    assert_eq!(
        part2(parse(parse::data(2022, 5).unwrap()).unwrap()).unwrap(),
        "BNTZFPMMW"
    );
}