Add d1 in rust

Trying to learn more rust, so this is probably rusty.
This commit is contained in:
IamTheFij 2021-12-03 08:55:07 -08:00
parent 619d22ef8a
commit 5bd5c5123e
6 changed files with 2102 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
target/

7
d01/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "d01"
version = "0.1.0"

8
d01/Cargo.toml Normal file
View File

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

2000
d01/input.txt Normal file

File diff suppressed because it is too large Load Diff

10
d01/input_short.txt Normal file
View File

@ -0,0 +1,10 @@
199
200
208
210
200
207
240
269
260
263

76
d01/src/main.rs Normal file
View File

@ -0,0 +1,76 @@
use std::collections::VecDeque;
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
fn part1() {
if let Ok(lines) = read_lines("input.txt") {
let mut last_val: Option<i32> = None;
let mut num_increase = 0;
for line in lines {
if let Ok(l) = line {
match l.parse::<i32>() {
Ok(val) => {
let increase;
match last_val {
Some(last_val) => increase = last_val < val,
None => increase = false,
}
// println!("{}: {}", val, increase);
if increase {
num_increase += 1;
}
last_val = Some(val);
}
Err(e) => println!("ERROR: Could not parse {}. {}", l, e),
}
}
}
println!("Part 1, All done! Num increased {}", num_increase);
}
}
fn part2() {
if let Ok(lines) = read_lines("input.txt") {
let mut num_increase = 0;
// If we have 3 values, pop from front and compare new number to the one read before
// pushing that to the back. If that is an increase, increment the increase value
let mut sliding_values: VecDeque<i32> = VecDeque::with_capacity(3);
for line in lines {
if let Ok(l) = line {
match l.parse::<i32>() {
Ok(val) => {
if sliding_values.len() < 3 {
sliding_values.push_back(val);
continue;
}
let outgoing = sliding_values.pop_front().unwrap();
let increase = val > outgoing;
if increase {
num_increase += 1;
}
sliding_values.push_back(val);
println!("{}: {}", val, increase);
}
Err(e) => println!("ERROR: Could not parse {}. {}", l, e),
}
}
}
println!("All done! Num increased {}", num_increase);
}
}
fn main() {
part1();
part2();
}