2021 day 1
This commit is contained in:
parent
804d6b6b92
commit
7b4cb884c1
5
2021/Cargo.lock
generated
Normal file
5
2021/Cargo.lock
generated
Normal file
@ -0,0 +1,5 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
[[package]]
|
||||
name = "advent-2021"
|
||||
version = "0.1.0"
|
9
2021/Cargo.toml
Normal file
9
2021/Cargo.toml
Normal file
@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "advent-2021"
|
||||
version = "0.1.0"
|
||||
authors = ["Joseph Montanaro <jfmontanaro@modg.org>"]
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
15
2021/src/lib.rs
Normal file
15
2021/src/lib.rs
Normal file
@ -0,0 +1,15 @@
|
||||
use std::io::{BufReader, BufRead};
|
||||
use std::fs::File;
|
||||
|
||||
|
||||
pub fn iter_nums(filename: &str) -> impl Iterator<Item=i32> {
|
||||
let file = File::open(filename).expect("File not found! Make sure that your current directory is the project root.");
|
||||
let reader = BufReader::new(file);
|
||||
|
||||
reader.lines().map(|line|
|
||||
line
|
||||
.expect("Couldn't split on lines I guess?")
|
||||
.parse::<i32>()
|
||||
.expect("Could not parse integer!")
|
||||
)
|
||||
}
|
33
2021/src/main.rs
Normal file
33
2021/src/main.rs
Normal file
@ -0,0 +1,33 @@
|
||||
mod lib;
|
||||
use lib::iter_nums;
|
||||
|
||||
|
||||
fn main() {
|
||||
day_one();
|
||||
}
|
||||
|
||||
|
||||
fn day_one() {
|
||||
let mut single_increases = 0;
|
||||
let mut window_increases = 0;
|
||||
let mut prev = (None, None, None);
|
||||
for n in iter_nums("data/01.txt") {
|
||||
if let Some(p) = prev.2 {
|
||||
// apparently we can't combine "if let" and regular boolean conditions
|
||||
if n > p {
|
||||
single_increases += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if let (Some(first), Some(second), Some(third)) = prev {
|
||||
if (n + second + third) > (first + second + third) {
|
||||
window_increases += 1;
|
||||
}
|
||||
}
|
||||
// would have forgotten this if not for the warning triggered by "let mut" without mutation
|
||||
prev = (prev.1, prev.2, Some(n));
|
||||
}
|
||||
|
||||
println!("One: {}", single_increases);
|
||||
println!("Two: {}", window_increases);
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user