Solved Day 1 challenges.

Took longer than I hoped it would. Not really familiar with some basic
Rust stuff (like file handling, etc.). Also rust-analyzer was really not
being nice. It crashed on StructOpt and keeps complaining about unsafe
being necessary in any and all format! statements.
This commit is contained in:
David Lenfesty 2021-11-30 23:05:57 -07:00
commit e6b3f045f8
4 changed files with 111 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/target
Cargo.lock
inputs/

9
Cargo.toml Normal file
View File

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

47
src/day1.rs Normal file
View File

@ -0,0 +1,47 @@
use std::collections::VecDeque;
/// Increments count if each sample is larger than the previous.
pub fn day1_p1(input: String) {
let mut prev = None;
let mut count: u32 = 0;
for line in input.lines() {
let cur = str::parse::<i64>(line).unwrap();
if let Some(prev) = prev {
if cur > prev {
count += 1;
}
}
prev = Some(cur);
}
println!("{}", count);
}
/// 3-sample windowing average (no need to average, just use sum here)
///
/// We need to start comparing when we have all of
pub fn day1_p2(input: String) {
let mut storage = VecDeque::with_capacity(5);
let mut count = 0;
for line in input.lines() {
let cur = str::parse::<i64>(line).unwrap();
storage.push_back(cur);
if storage.len() == 4 {
let prev_window: i64 = storage.iter().take(3).sum();
let cur_window: i64 = storage.iter().skip(1).take(3).sum();
if cur_window > prev_window {
count += 1;
}
storage.pop_front();
}
}
println!("{}", count);
}

52
src/main.rs Normal file
View File

@ -0,0 +1,52 @@
use clap::{App, Arg};
mod day1;
fn main() {
let matches = App::new("AOC 2021 Code")
.version("0.1")
.author("David Lenfesty <lenfesty@ualberta.ca")
.about("My 2021 Advent of Code work.")
.arg(
Arg::with_name("day")
.short("d")
.long("day")
.required(true)
.takes_value(true),
)
.arg(
Arg::with_name("part")
.short("p")
.long("part")
.required(true)
.takes_value(true),
)
.get_matches();
// TODO bounds checking :P
let day = matches.value_of("day").unwrap_or("1");
let day = str::parse::<u8>(day).expect("Invalid day provided (1-25 expected)");
let part = matches.value_of("part").unwrap_or("1");
let part = str::parse::<u8>(part).expect("Invalid part provided (1 or 2 expected)");
let input = read_input(day, part).unwrap();
match day {
1 => match part {
1 => day1::day1_p1(input),
2 => day1::day1_p2(input),
_ => (),
},
_ => println!("Day {} not completed yet!", day),
}
}
// TODO do the inputs ever change inside of a day?
/// Read inputs into a string
fn read_input(day: u8, part: u8) -> std::io::Result<String> {
std::fs::read_to_string(format!(
"inputs/day{}p{}",
day, part
))
}