summaryrefslogtreecommitdiffstats
path: root/src/bin/2021/day25.rs
blob: 135f6b32ecbd103d719d0e937ece2d63f353ee96 (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
use advent_of_code::prelude::*;

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Cell {
    Down,
    Right,
    None,
}

impl Default for Cell {
    fn default() -> Self {
        Self::None
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Map {
    grid: Grid<Cell>,
}

impl Map {
    fn step(&self) -> Self {
        self.step_east().step_south()
    }

    fn step_east(&self) -> Self {
        let mut step = self.clone();
        for ((Row(row), Col(col)), cell) in self.grid.indexed_cells() {
            if *cell == Cell::Right {
                let mut next = col + 1;
                if next >= self.grid.cols().0 {
                    next = 0;
                }
                if self.grid[Row(row)][Col(next)] == Cell::None {
                    step.grid[Row(row)][Col(next)] = Cell::Right;
                    step.grid[Row(row)][Col(col)] = Cell::None;
                }
            }
        }
        step
    }

    fn step_south(&self) -> Self {
        let mut step = self.clone();
        for ((Row(row), Col(col)), cell) in self.grid.indexed_cells() {
            if *cell == Cell::Down {
                let mut next = row + 1;
                if next >= self.grid.rows().0 {
                    next = 0;
                }
                if self.grid[Row(next)][Col(col)] == Cell::None {
                    step.grid[Row(next)][Col(col)] = Cell::Down;
                    step.grid[Row(row)][Col(col)] = Cell::None;
                }
            }
        }
        step
    }
}

pub fn parse(fh: File) -> Result<Map> {
    Ok(Map {
        grid: parse::grid(parse::raw_lines(fh), |b, _, _| match b {
            b'v' => Cell::Down,
            b'>' => Cell::Right,
            b'.' => Cell::None,
            _ => panic!("unknown cell {}", b),
        }),
    })
}

pub fn part1(map: Map) -> Result<u64> {
    let mut prev = map;
    let mut i = 0;
    loop {
        i += 1;
        let next = prev.step();
        if next == prev {
            break;
        }
        prev = next;
    }
    Ok(i)
}

pub fn part2(_: Map) -> Result<i64> {
    Ok(0)
}

#[test]
fn test() {
    assert_eq!(
        part1(parse(parse::data(2021, 25).unwrap()).unwrap()).unwrap(),
        482
    );
}