Added day 1 code for part 1 and 2

Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
This commit is contained in:
Louis Vallat 2021-12-03 10:41:12 +01:00
commit c73c41bf4c
No known key found for this signature in database
GPG Key ID: 0C87282F76E61283
4 changed files with 2047 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
target
Cargo.lock

8
day1/Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "day1"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

2000
day1/input Normal file

File diff suppressed because it is too large Load Diff

37
day1/src/main.rs Normal file
View File

@ -0,0 +1,37 @@
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));
}
}