diff options
author | Jesse Luehrs <doy@tozt.net> | 2022-12-11 21:59:21 -0500 |
---|---|---|
committer | Jesse Luehrs <doy@tozt.net> | 2022-12-11 22:16:30 -0500 |
commit | e2d219b331a878bbb3c9dcef9ea4e218b2e3ee06 (patch) | |
tree | 93e418011c45cab8d4070d3d33b377a9364f4a27 /src/bin/2021/day2.rs | |
parent | 179467096141b7e8f67d63b89fd21e779a564fe6 (diff) | |
download | advent-of-code-e2d219b331a878bbb3c9dcef9ea4e218b2e3ee06.tar.gz advent-of-code-e2d219b331a878bbb3c9dcef9ea4e218b2e3ee06.zip |
refactor
Diffstat (limited to 'src/bin/2021/day2.rs')
-rw-r--r-- | src/bin/2021/day2.rs | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/src/bin/2021/day2.rs b/src/bin/2021/day2.rs new file mode 100644 index 0000000..5ae3596 --- /dev/null +++ b/src/bin/2021/day2.rs @@ -0,0 +1,73 @@ +use advent_of_code::prelude::*; + +pub enum Command { + Forward(i64), + Down(i64), + Up(i64), +} + +pub fn parse(fh: File) -> Result<impl Iterator<Item = Command>> { + Ok(parse::raw_lines(fh).map(|line| { + if let Some(n) = line.strip_prefix("forward ") { + Command::Forward(n.parse().unwrap()) + } else if let Some(n) = line.strip_prefix("down ") { + Command::Down(n.parse().unwrap()) + } else if let Some(n) = line.strip_prefix("up ") { + Command::Up(n.parse().unwrap()) + } else { + panic!("couldn't parse line: {}", line); + } + })) +} + +pub fn part1(commands: impl Iterator<Item = Command>) -> Result<i64> { + let mut horizontal = 0; + let mut vertical = 0; + for command in commands { + match command { + Command::Forward(n) => { + horizontal += n; + } + Command::Down(n) => { + vertical += n; + } + Command::Up(n) => { + vertical -= n; + } + } + } + Ok(horizontal * vertical) +} + +pub fn part2(commands: impl Iterator<Item = Command>) -> Result<i64> { + let mut aim = 0; + let mut horizontal = 0; + let mut vertical = 0; + for command in commands { + match command { + Command::Forward(n) => { + horizontal += n; + vertical += aim * n; + } + Command::Down(n) => { + aim += n; + } + Command::Up(n) => { + aim -= n; + } + } + } + Ok(horizontal * vertical) +} + +#[test] +fn test() { + assert_eq!( + part1(parse(parse::data(2021, 2).unwrap()).unwrap()).unwrap(), + 1694130 + ); + assert_eq!( + part2(parse(parse::data(2021, 2).unwrap()).unwrap()).unwrap(), + 1698850445 + ); +} |