-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08.rs
94 lines (82 loc) · 2.16 KB
/
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
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
/*
* Day 8: Treetop Tree House
* See [https://adventofcode.com/2022/day/8]
*/
fn input_grid(input: &str) -> Vec<&[u8]> {
input.lines().map(str::as_bytes).collect::<Vec<&[u8]>>()
}
pub fn part_1(input: &str) -> Option<usize> {
let grid = input_grid(input);
let lh = grid.len() - 1;
let lw = grid[0].len() - 1;
let mut sum = (lw + lh) * 2;
for j in 1..lh {
let row = grid[j];
for i in 1..lw {
let el = row[i];
if el == b'0' {
continue;
}
if grid[..j].iter().rev().all(|z| el > z[i])
|| grid[j+1..].iter().all(|z| el > z[i])
|| row[..i].iter().rev().all(|z| el > *z)
|| row[i+1..].iter().all(|z| el > *z) {
sum += 1;
}
}
}
Some(sum)
}
pub fn part_2(input: &str) -> Option<usize> {
let grid = input_grid(input);
let lh = grid.len() - 1;
let lw = grid[0].len() - 1;
let mut vmax: usize = 0;
for j in 1..lh {
let row = grid[j];
for i in 1..lw {
let el = row[i];
let rowfn = |&z| el <= z;
let gridln = |&z: &&[u8]| el <= z[i];
let t = if let Some(x) = &grid[..j].iter().rev().position(gridln) {
x + 1
} else {
j
};
let l = if let Some(x) = &row[..i].iter().rev().position(rowfn) {
x + 1
} else {
i
};
let r = if let Some(x) = &row[i + 1..].iter().position(rowfn) {
x + 1
} else {
lh - i
};
let b = if let Some(x) = &grid[j + 1..].iter().position(gridln) {
x + 1
} else {
lw - j
};
let val = t * l * r * b;
if vmax < val {
vmax = val;
}
}
}
Some(vmax)
}
aoc2022::solve!(part_1, part_2);
#[cfg(test)]
mod tests {
use super::*;
use aoc2022::assert_ex;
#[test]
fn test_part_1() {
assert_ex!(part_1, 21);
}
#[test]
fn test_part_2() {
assert_ex!(part_2, 8);
}
}