Skip to content

Commit cb9448e

Browse files
author
mflinn-broad
committed
day 9 part 1
1 parent 2721d28 commit cb9448e

File tree

4 files changed

+81
-0
lines changed

4 files changed

+81
-0
lines changed

src/days/day8.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,28 @@ fn part_2(input: &Vec<(Vec<&str>, Vec<&str>)>) -> u32 {
130130
})
131131
.sum()
132132
}
133+
134+
#[cfg(test)]
135+
mod tests {
136+
use super::*;
137+
extern crate test;
138+
use test::Bencher;
139+
140+
#[bench]
141+
fn bench_part_1(b: &mut Bencher) {
142+
let raw_input = util::read_input("inputs/day8.txt").unwrap();
143+
b.iter(|| {
144+
let mut input = process(&raw_input);
145+
part_1(&mut input);
146+
});
147+
}
148+
149+
#[bench]
150+
fn bench_part_2(b: &mut Bencher) {
151+
let raw_input = util::read_input("inputs/day8.txt").unwrap();
152+
b.iter(|| {
153+
let input = process(&raw_input);
154+
part_2(&input);
155+
});
156+
}
157+
}

src/days/day9.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
use crate::util;
2+
3+
pub fn run() {
4+
let raw_input = util::read_input("inputs/day9.txt").unwrap();
5+
let input = process(&raw_input);
6+
println!("Part 1: {:?}", part_1(&input));
7+
}
8+
9+
pub fn process(input: &str) -> Vec<Vec<u8>> {
10+
input
11+
.lines()
12+
.map(|line| {
13+
line.trim()
14+
.chars()
15+
.map(|num| num.to_string().parse().unwrap())
16+
.collect()
17+
})
18+
.collect()
19+
}
20+
21+
fn is_local_minima(target: u8, adjacents: Vec<u8>) -> bool {
22+
adjacents.iter()
23+
.all(|val| target < *val)
24+
}
25+
26+
fn part_1(input: &Vec<Vec<u8>>) -> u32 {
27+
input.iter()
28+
.enumerate()
29+
.fold(0, |risk_score, (row_idx, row)| {
30+
risk_score + row.iter()
31+
.enumerate()
32+
.fold(0, |row_risk, (col, height)| {
33+
let mut adjacents: Vec<u8> = Vec::new();
34+
if row_idx != 0 {
35+
adjacents.push(input[row_idx - 1][col]);
36+
}
37+
if col != 0 {
38+
adjacents.push(input[row_idx][col - 1]);
39+
}
40+
if row_idx != (input.len() - 1) {
41+
adjacents.push(input[row_idx + 1][col]);
42+
}
43+
if col != (input[0].len() - 1) {
44+
adjacents.push(input[row_idx][col + 1]);
45+
}
46+
if is_local_minima(*height, adjacents) {
47+
row_risk + (*height as u32) + 1
48+
} else {
49+
row_risk
50+
}
51+
})
52+
})
53+
}

src/days/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ pub mod day5;
66
pub mod day6;
77
pub mod day7;
88
pub mod day8;
9+
pub mod day9;

src/main.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,6 @@ fn main() {
1717
day7::run();
1818
println!("Day 8 --------");
1919
day8::run();
20+
println!("Day 9 ---------");
21+
day9::run();
2022
}

0 commit comments

Comments
 (0)