Added year directories for advent of code

This commit is contained in:
2022-12-02 13:37:41 +01:00
parent 27d00340b9
commit 6c9525248e
31 changed files with 275 additions and 0 deletions

1000
advent_of_code/2021/d2/2.txt Normal file

File diff suppressed because it is too large Load Diff

7
advent_of_code/2021/d2/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 = "d2"
version = "0.1.0"

View File

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

View File

@@ -0,0 +1,64 @@
use std::io::{self, BufRead};
use std::path::Path;
use std::fs::File;
fn main(){
println!("Advent of Code #2!\n");
let path = Path::new("./2.txt");
let display = path.display();
let file = match File::open(&path) {
Err(why) => panic!("Couldn't open {}: {}", display, why),
Ok(file) => file,
};
let lines = io::BufReader::new(file).lines();
let mut instructions = Vec::<(String, u32)>::new();
for line in lines {
if let Ok(l) = line {
let mut words_iter = l.split_whitespace();
let direction = words_iter.next().unwrap().to_string();
let distance = words_iter.next().unwrap().parse::<u32>().unwrap();
instructions.push((direction, distance));
}
}
let mut depth = 0;
let mut position = 0;
for (direction, distance) in &instructions {
match direction.as_str() {
"forward" => position += distance,
"up" => depth -= distance,
"down" => depth += distance,
s => println!("Stumbled upon unknown input: {}", s),
}
}
println!("Position of {} * depth of {} equals {}", position, depth, position * depth);
// Now for the second part of day 2
// So instead of just adding to the depth immediately through the up and down commands, we now use
// a so-called aim
depth = 0;
position = 0;
let mut aim = 0;
for (direction, distance) in &instructions {
match direction.as_str() {
"forward" => {
depth += aim * distance;
position += distance
},
"up" => aim -= distance,
"down" => aim += distance,
s => println!("Stumbled upon unknown input: {}", s),
}
}
println!("Position of {} * depth of {} equals {}", position, depth, position * depth);
}