advent-of-code-2021/day1/src/main.rs
Louis Vallat c73c41bf4c
Added day 1 code for part 1 and 2
Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
2021-12-03 10:41:12 +01:00

38 lines
1.1 KiB
Rust

use std::{fs, env, collections::BTreeMap};
fn read_input(path: &str) -> String {
return fs::read_to_string(path).expect("Cannot read file.");
}
fn parse_input(s: &str) -> Vec<i32> {
return s.split("\n").into_iter().filter_map(|f| f.parse::<i32>().ok()).collect::<Vec<i32>>();
}
fn get_increase_nb(e: &Vec<i32>) -> i32 {
let mut n = 0;
for i in 1..e.len() {
n += if e[i] > e[i - 1] { 1 } else { 0 };
}
return n;
}
fn get_sums(v: &Vec<i32>) -> BTreeMap<usize, i32> {
let mut sums = BTreeMap::new();
for i in 0..(v.len() - 2) {
sums.insert(i, v[i] + v[i + 1] + v[i + 2]);
}
return sums;
}
fn main() {
let args: Vec<String> = env::args().collect();
for arg in args.iter().skip(1) {
let vec_in = parse_input(&read_input(&arg));
println!("[{}]", &arg);
println!("\t[Part 1] => Answer is '{}'.", get_increase_nb(&vec_in));
let map = get_sums(&vec_in).iter().map(|e| e.1.to_owned()).collect::<Vec<i32>>();
println!("\t[Part 2] => Answer is '{}'.", get_increase_nb(&map));
}
}