diff --git a/src/day2.rs b/src/day2.rs new file mode 100644 index 0000000..63d8dd3 --- /dev/null +++ b/src/day2.rs @@ -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::().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::().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); +} diff --git a/src/main.rs b/src/main.rs index 535133e..9437bda 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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::(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 { - std::fs::read_to_string(format!( - "inputs/day{}p{}", - day, part - )) +fn read_input(day: u8) -> std::io::Result { + std::fs::read_to_string(format!("inputs/day{}", day)) }