Finished day 2

This commit is contained in:
David Lenfesty 2021-12-02 12:39:32 -07:00
parent 372bc43623
commit e64edbd201
2 changed files with 62 additions and 6 deletions

53
src/day2.rs Normal file
View File

@ -0,0 +1,53 @@
struct Position {
pub x: i64,
pub y: i64,
pub z: i64,
}
impl std::default::Default for Position {
fn default() -> Self {
Self { x: 0, y: 0, z: 0 }
}
}
pub fn part1(input: String) {
let mut pos = Position::default();
for line in input.lines() {
let mut command = line.split(' ');
let dir = command.next().unwrap();
let distance = command.next().unwrap().parse::<i64>().unwrap();
match dir {
"forward" => pos.x += distance,
"up" => pos.z += distance,
"down" => pos.z -= distance,
_ => panic!("Invalid input!"),
}
}
println!("{}", pos.x * -pos.z);
}
pub fn part2(input: String) {
let mut pos = Position::default();
let mut attitude = 0i64;
for line in input.lines() {
let mut command = line.split(' ');
let dir = command.next().unwrap();
let distance = command.next().unwrap().parse::<i64>().unwrap();
match dir {
"forward" => {
pos.x += distance;
pos.z += distance * attitude;
}
"up" => attitude += distance,
"down" => attitude -= distance,
_ => panic!("Invalid input!"),
}
}
println!("{}", pos.x * -pos.z);
}

View File

@ -1,6 +1,7 @@
use clap::{App, Arg};
mod day1;
mod day2;
fn main() {
let matches = App::new("AOC 2021 Code")
@ -30,7 +31,7 @@ fn main() {
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();
let input = read_input(day).unwrap();
match day {
1 => match part {
@ -38,15 +39,17 @@ fn main() {
2 => day1::day1_p2(input),
_ => (),
},
2 => match part {
1 => day2::part1(input),
2 => day2::part2(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
))
fn read_input(day: u8) -> std::io::Result<String> {
std::fs::read_to_string(format!("inputs/day{}", day))
}