From b36eb44b3c4a3cf12e7a99543c8fc6b7dabb5679 Mon Sep 17 00:00:00 2001 From: Rokas Puzonas Date: Fri, 3 Dec 2021 01:29:03 +0200 Subject: [PATCH] feat: solve day 2 part 2 --- src/day2.rs | 31 +++++++++++++++++++++++++++++++ src/main.rs | 4 ++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/day2.rs b/src/day2.rs index a4d4b84..f80bf9c 100644 --- a/src/day2.rs +++ b/src/day2.rs @@ -53,6 +53,23 @@ pub fn part1(commands: &[CommandLine]) -> u32 { return depth * horizontal; } +pub fn part2(commands: &[CommandLine]) -> u32 { + let mut depth = 0; + let mut horizontal = 0; + let mut aim = 0; + for command in commands { + match command.0 { + Command::Up => aim -= command.1, + Command::Down => aim += command.1, + Command::Forward => { + horizontal += command.1; + depth += aim * command.1; + } + } + } + return depth * horizontal; +} + #[cfg(test)] mod tests { use super::*; @@ -70,5 +87,19 @@ mod tests { let result = part1(&commands); assert_eq!(result, 150); } + + #[test] + fn part2_example() { + let commands = [ + CommandLine(Command::Forward, 5), + CommandLine(Command::Down, 5), + CommandLine(Command::Forward, 8), + CommandLine(Command::Up, 3), + CommandLine(Command::Down, 8), + CommandLine(Command::Forward, 2) + ]; + let result = part2(&commands); + assert_eq!(result, 900) + } } diff --git a/src/main.rs b/src/main.rs index f35762e..f303488 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,9 +10,9 @@ fn main() { // let result2 = day1::part2(&input); let result1 = day2::part1(&input); - // let result2 = day2::part2(&input); + let result2 = day2::part2(&input); println!("Part 1 result: {}", result1); - // println!("Part 2 result: {}", result2); + println!("Part 2 result: {}", result2); }