Added year directories for advent of code
This commit is contained in:
64
advent_of_code/2021/d2/src/main.rs
Normal file
64
advent_of_code/2021/d2/src/main.rs
Normal 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);
|
||||
}
|
||||
Reference in New Issue
Block a user