diff --git a/2021/src/day2.rs b/2021/src/day2.rs index fb4746d..744b6e3 100644 --- a/2021/src/day2.rs +++ b/2021/src/day2.rs @@ -40,11 +40,10 @@ impl<'a> FromStr for MoveCmd { } -pub fn part1(data: &str) -> eyre::Result<()> { +fn part1(commands: &Vec) -> i32 { let mut horiz = 0; // how many units forward let mut vert = 0; // how many units DOWN (so flipped) - for res in data.parse_lines::() { - let cmd = res?; + for cmd in commands { match cmd.dir { Direction::Forward => horiz += cmd.value, Direction::Up => vert -= cmd.value, @@ -52,17 +51,15 @@ pub fn part1(data: &str) -> eyre::Result<()> { } } - println!("One: {}", horiz * vert); - Ok(()) + horiz * vert } -pub fn part2(data: &str) -> eyre::Result<()> { +fn part2(commands: &Vec) -> i32 { let mut horiz = 0; let mut vert = 0; let mut aim = 0; - for res in data.parse_lines::() { - let cmd = res?; + for cmd in commands { match cmd.dir { Direction::Down => aim += cmd.value, // flipped again Direction::Up => aim -= cmd.value, @@ -73,6 +70,17 @@ pub fn part2(data: &str) -> eyre::Result<()> { } } - println!("Two: {}", horiz * vert); + horiz * vert +} + + +pub fn run(data: &str) -> eyre::Result<()> { + let mut commands = Vec::new(); + for res in data.parse_lines::() { + commands.push(res?); + } + + println!("One: {}", part1(&commands)); + println!("Two: {}", part2(&commands)); Ok(()) } diff --git a/2021/src/main.rs b/2021/src/main.rs index 6f956e7..50b72bc 100644 --- a/2021/src/main.rs +++ b/2021/src/main.rs @@ -1,7 +1,7 @@ use color_eyre::eyre; mod lib; -use lib::{load, ParseLines}; +use lib::load; mod day2; @@ -10,37 +10,5 @@ mod day2; fn main() -> eyre::Result<()> { let data = load("data/02.txt")?; - day2::part1(&data)?; - day2::part2(&data) -} - - -#[allow(dead_code)] -fn day_one() -> eyre::Result<()> { - let data = load("data/01.txt")?; - - let mut single_increases = 0; - let mut window_increases = 0; - let mut prev = (None, None, None); - for res in data.parse_lines::() { - let n = res?; - if let Some(p) = prev.2 { - // apparently we can't combine "if let" and regular boolean conditions - if n > p { - single_increases += 1; - } - } - - if let (Some(first), Some(second), Some(third)) = prev { - if (n + second + third) > (first + second + third) { - window_increases += 1; - } - } - // would have forgotten this if not for the warning triggered by "let mut" without mutation - prev = (prev.1, prev.2, Some(n)); - } - - println!("One: {}", single_increases); - println!("Two: {}", window_increases); - Ok(()) + day2::run(&data) }