1
0
Fork 0
aoc2021/src/main.rs

67 lines
1.5 KiB
Rust
Raw Permalink Normal View History

2021-12-01 05:51:55 +00:00
#![feature(test)]
extern crate test;
2021-12-03 05:38:45 +00:00
const INPUTS: [&'static str; 2] = [
2021-12-05 05:24:30 +00:00
include_str!("../inputs/sample.txt"),
include_str!("../inputs/input.txt"),
2021-12-03 05:38:45 +00:00
];
2021-12-02 05:14:07 +00:00
2021-12-09 05:08:37 +00:00
fn parse_input(input: &'static str) -> Vec<Vec<u8>> {
input
.lines()
.filter(|&x| !x.is_empty())
.map(|line| line.bytes().map(|x| x - b'0').collect())
.collect()
2021-12-04 05:41:16 +00:00
}
2021-12-03 13:33:56 +00:00
2021-12-09 05:08:37 +00:00
const NEIGHBOURS: [[i32; 2]; 4] = [[-1, 0], [1, 0], [0, -1], [0, 1]];
2021-12-09 05:00:17 +00:00
2021-12-09 05:08:37 +00:00
fn solution(input: Vec<Vec<u8>>) -> i32 {
let mut answer = 0;
2021-12-08 17:50:11 +00:00
2021-12-09 05:08:37 +00:00
let m = input.len();
let n = input[0].len();
2021-12-09 05:00:17 +00:00
2021-12-09 05:08:37 +00:00
for i in 0..m {
for j in 0..n {
let mut is_minimum = true;
2021-12-08 17:50:11 +00:00
2021-12-09 05:08:37 +00:00
for &neighbour in NEIGHBOURS.iter() {
let x = i as i32 + neighbour[0];
let y = j as i32 + neighbour[1];
2021-12-08 17:50:11 +00:00
2021-12-09 05:08:37 +00:00
if x < 0 || y < 0 || x >= m as i32 || y >= n as i32 {
continue;
}
2021-12-09 05:00:17 +00:00
2021-12-09 05:08:37 +00:00
if input[i][j] >= input[x as usize][y as usize] {
is_minimum = false;
2021-12-08 17:50:11 +00:00
}
2021-12-08 13:21:58 +00:00
}
2021-12-08 17:50:11 +00:00
2021-12-09 05:08:37 +00:00
if is_minimum {
answer += input[i][j] as i32 + 1;
}
}
2021-12-03 05:38:45 +00:00
}
2021-12-08 13:21:58 +00:00
answer
2021-12-01 05:51:55 +00:00
}
fn main() {
2021-12-04 05:41:16 +00:00
for input in INPUTS {
2021-12-05 05:24:30 +00:00
let input = parse_input(input);
2021-12-07 08:53:21 +00:00
let result = solution(input);
2021-12-04 05:41:16 +00:00
println!("Result {}", result);
}
2021-12-01 05:16:08 +00:00
}
2021-12-01 05:51:55 +00:00
#[bench]
fn solution_bench(b: &mut test::Bencher) {
2021-12-09 05:08:37 +00:00
let input = parse_input(INPUTS[1]);
2021-12-01 05:51:55 +00:00
b.iter(|| {
2021-12-09 05:08:37 +00:00
let result = solution(input.clone());
2021-12-04 05:41:16 +00:00
test::black_box(result);
2021-12-01 05:51:55 +00:00
})
}