From: Greg Burri Date: Sat, 4 Dec 2021 21:23:08 +0000 (+0100) Subject: Day 2 part 2 X-Git-Url: https://git.euphorik.ch/?a=commitdiff_plain;h=3236121d6985537b8d0646bdb5925f58fa705d1e;p=advent_of_code_2021.git Day 2 part 2 --- diff --git a/src/day02.rs b/src/day02.rs index 44f8ce3..732d179 100644 --- a/src/day02.rs +++ b/src/day02.rs @@ -7,6 +7,7 @@ pub enum Movement { pub struct Position { pub horizontal: i32, + pub aim: i32, pub depth: i32, } @@ -28,12 +29,15 @@ pub fn parse_movements(movements: &str) -> Vec { } pub fn get_final_position(movements: &[Movement]) -> Position { - let mut pos = Position { horizontal: 0, depth: 0 }; + let mut pos = Position { horizontal: 0, aim: 0, depth: 0 }; for m in movements { match m { - Movement::Forward(d) => pos.horizontal += *d as i32, - Movement::Down(d) => pos.depth += *d as i32, - Movement::Up(d) => pos.depth -= *d as i32, + Movement::Forward(d) => { + pos.horizontal += *d as i32; + pos.depth += pos.aim * *d as i32; + }, + Movement::Down(d) => pos.aim += *d as i32, + Movement::Up(d) => pos.aim -= *d as i32, } } pos @@ -69,10 +73,21 @@ mod tests { forward 2" ); let final_position = get_final_position(&commands); - assert_eq!(final_position.horizontal * final_position.depth, 150); + assert_eq!(final_position.horizontal * final_position.aim, 150); } #[test] fn part2() { + let commands = + parse_movements( + "forward 5 + down 5 + forward 8 + up 3 + down 8 + forward 2" + ); + let final_position = get_final_position(&commands); + assert_eq!(final_position.horizontal * final_position.depth, 900); } } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index eb070cb..e3a099a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,7 +14,7 @@ fn day01() -> String { fn day02() -> String { let movements = day02::parse_movements(&fs::read_to_string("data/day02.input").unwrap()); let final_position = day02::get_final_position(&movements); - format!("part1: {}, part2: {}", final_position.horizontal * final_position.depth, "") + format!("part1: {}, part2: {}", final_position.horizontal * final_position.aim, final_position.horizontal * final_position.depth) } fn format_micros(t: u128) -> String {