-
Notifications
You must be signed in to change notification settings - Fork 3
/
day_08.rs
66 lines (55 loc) · 1.74 KB
/
day_08.rs
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
use common::{solution, Answer};
solution!("Treetop Tree House", 8);
fn part_a(input: &str) -> Answer {
let trees = parse_trees(input);
let mut count = 0;
for row in 0..trees.len() {
for col in 0..trees[row].len() {
let height = trees[row][col];
if trees[..row].iter().all(|x| x[col] < height)
|| trees[row][..col].iter().all(|x| x < &height)
|| trees[row + 1..].iter().all(|x| x[col] < height)
|| trees[row][col + 1..].iter().all(|x| x < &height)
{
count += 1;
}
}
}
count.into()
}
fn part_b(input: &str) -> Answer {
let trees = parse_trees(input);
let mut count = 0;
for row in 0..trees.len() {
for col in 0..trees[row].len() {
let mut ctx = (1, trees[row][col]);
process_slice(&mut ctx, trees[..row].iter().map(|x| x[col]).rev());
process_slice(&mut ctx, trees[row][..col].iter().rev().copied());
process_slice(&mut ctx, trees[row + 1..].iter().map(|x| x[col]));
process_slice(&mut ctx, trees[row][col + 1..].iter().copied());
count = count.max(ctx.0);
}
}
count.into()
}
fn parse_trees(inp: &str) -> Vec<Vec<usize>> {
inp.lines()
.map(|i| {
i.chars()
.filter(|x| x.is_ascii_digit())
.filter_map(|x| x.to_digit(10))
.map(|x| x as usize)
.collect()
})
.collect()
}
fn process_slice((local_best, height): &mut (usize, usize), iter: impl Iterator<Item = usize>) {
let mut score = 0;
for i in iter {
score += 1;
if i >= *height {
break;
}
}
*local_best *= score;
}