summaryrefslogtreecommitdiff
path: root/2022/rust/day08/src/main.rs
blob: 1a17d937cdde82f5c5866deef7a242eae1c68d52 (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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use {
    anyhow::{
        anyhow,
        Context,
        Result,
    },
    std::{
        env::args,
        fs::File,
        io::{
            BufRead,
            BufReader,
        },
        path::Path,
    },
};

#[derive(Clone,Copy,Debug)]
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

#[derive(Clone,Debug,PartialEq)]
struct Position {
    x: usize,
    y: usize,
}

#[derive(Debug)]
struct Trees {
    size: usize,
    heights: Vec<u8>,
}

impl Trees {
    fn new_with_size(size: usize, heights: Vec<u8>) -> Result<Self> {
        let len = heights.len();
        if size * size == len {
            Ok(Self { size, heights, })
        } else {
            Err(anyhow!("Could not create Trees: {size}² ≠ {len}."))
        }
    }

    fn size(&self) -> usize {
        self.size
    }

    fn height(&self, position: &Position) -> u8 {
        let x = position.x as usize;
        let y = position.y as usize;
        if let Some(height) = self.heights.get(y * self.size + x) {
            *height
        } else {
            panic!("Invalid attempt to access element x: {x}, y: {y} in Trees with size: {}.",
                self.size);
        }
    }

    fn is_visible(&self, position: &Position, direction: Direction) -> bool {
        let target_height = self.height(position);

        match direction {
            Direction::Up => {
                for distance in 0..position.y {
                    let cmp_height = self.height(&Position { x: position.x, y: distance });
                    if cmp_height >= target_height {
                        return false;
                    }
                }
            },
            Direction::Down => {
                for distance in (position.y + 1)..self.size {
                    let cmp_height = self.height(&Position { x: position.x, y: distance });
                    if cmp_height >= target_height {
                        return false;
                    }
                }
            },
            Direction::Left => {
                for distance in 0..position.x {
                    let cmp_height = self.height(&Position { x: distance, y: position.y });
                    if cmp_height >= target_height {
                        return false;
                    }
                }
            },
            Direction::Right => {
                for distance in (position.x + 1)..self.size {
                    let cmp_height = self.height(&Position { x: distance, y: position.y });
                    if cmp_height >= target_height {
                        return false;
                    }
                }
            },
        }
        true
    }

    fn distance(&self, start: &Position, direction: &Direction) -> usize {
        let target_height = self.height(start);
        let position = start.clone();
        let mut distance = 0;

        match direction {
            Direction::Up => {
                for i in (0..position.y).rev() {
                    let cmp_height = self.height(&Position { x: position.x, y: i });
                    distance += 1;
                    if cmp_height >= target_height {
                        break;
                    }
                }
            },
            Direction::Down => {
                for i in (position.y + 1)..self.size {
                    let cmp_height = self.height(&Position { x: position.x, y: i });
                    distance += 1;
                    if cmp_height >= target_height {
                        break;
                    }
                }
            },
            Direction::Left => {
                for i in (0..position.x).rev() {
                    let cmp_height = self.height(&Position { x: i, y: position.y });
                    distance += 1;
                    if cmp_height >= target_height {
                        break;
                    }
                }
            },
            Direction::Right => {
                for i in (position.x + 1)..self.size {
                    let cmp_height = self.height(&Position { x: i, y: position.y });
                    distance += 1;
                    if cmp_height >= target_height {
                        break;
                    }
                }
            },
        }
        distance
    }
}

fn read_input<T: AsRef<Path>>(filename: T) -> Result<Trees> {
    let reader = BufReader::new(File::open(filename)?);
    let mut size = 0;

    let heights = reader.lines().map(
        |v| {
            size += 1;
            let s = v?;
            s.bytes().map(|height| match height {
                b'0'..=b'9' => Ok(height - b'0'),
                _ => Err(anyhow!("Invalid digit: '{height}'")),
            }).collect::<Result<Vec<_>>>()
        }
    ).collect::<Result<Vec<_>>>()?.into_iter().flatten().collect();

    Trees::new_with_size(size, heights)
}

fn part1(input: &Trees) -> Result<usize> {
    let mut positions: Vec<Position> = vec![];

    for direction in [Direction::Up, Direction::Down, Direction::Left, Direction::Right].iter() {
        for y in 0..input.size() {
            for x in 0..input.size() {
                let position = Position { x, y };
                if input.is_visible(&position, *direction) && !positions.contains(&position) {
                    positions.push(position);
                }
            }
        }
    }

    Ok(positions.len())
}

fn part2(input: &Trees) -> Result<usize> {
    (0..input.size()).flat_map(|y|
        (0..input.size()).map(move |x| {
            let position = Position { x, y };
            [Direction::Up, Direction::Down, Direction::Left, Direction::Right].iter()
            .map(|direction| {
                input.distance(&position, direction)
            }).product()
        }
    )).max().ok_or_else(|| anyhow!("Really, a tree patch with a 1-by-1 grid?"))
}

fn main() -> Result<()> {
    let ( do_part_1, do_part_2 ) = aoc::do_parts();

    let filename = args().nth(1).ok_or_else(|| anyhow!("Missing input filename"))?;
    let input = read_input(filename).context("Could not read input")?;
    if do_part_1 {
        let solution = part1(&input).context("No solution for part 1")?;
        println!("Part1, solution found to be: {}", solution);
    }
    if do_part_2 {
        let solution = part2(&input).context("No solution for part 2")?;
        println!("Part2, solution found to be: {}", solution);
    }
    Ok(())
}