diff options
-rw-r--r-- | y2021/src/d02.rs | 21 | ||||
-rw-r--r-- | y2021/src/main.rs | 3 |
2 files changed, 24 insertions, 0 deletions
diff --git a/y2021/src/d02.rs b/y2021/src/d02.rs index f844106..bcd6d41 100644 --- a/y2021/src/d02.rs +++ b/y2021/src/d02.rs @@ -15,6 +15,22 @@ pub fn part1<T: Iterator<Item = String>>(e: T) -> usize { h * d } +pub fn part2<T: Iterator<Item = String>>(e: T) -> usize { + let (h, d, _) = e.fold((0, 0, 0), |(h, d, a), l| { + let (td, tv) = l.split_once(" ").unwrap(); + let tv = tv.parse::<usize>().unwrap(); + + match td { + "forward" => (h + tv, d + (a * tv), a), + "down" => (h, d, a + tv), + "up" => (h, d, a - tv), + _ => unreachable!(), + } + }); + + h * d +} + #[cfg(test)] mod tests { use super::*; @@ -32,4 +48,9 @@ mod tests { fn test() { assert_eq!(150, part1(EX.iter().map(|x| x.to_string()))); } + + #[test] + fn test2() { + assert_eq!(900, part2(EX.iter().map(|x| x.to_string()))); + } } diff --git a/y2021/src/main.rs b/y2021/src/main.rs index 4605cdd..925ba54 100644 --- a/y2021/src/main.rs +++ b/y2021/src/main.rs @@ -25,5 +25,8 @@ fn main() { if args.is_empty() || args.contains("2") { let a = d02::part1(get_input_for_day(2)); println!("2021: day 2 part 1: {}", a); + + let a = d02::part2(get_input_for_day(2)); + println!("2021: day 2 part 2: {}", a); } } |