summaryrefslogtreecommitdiffstats
path: root/src/2021/2/mod.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/2021/2/mod.rs')
-rw-r--r--src/2021/2/mod.rs73
1 files changed, 54 insertions, 19 deletions
diff --git a/src/2021/2/mod.rs b/src/2021/2/mod.rs
index e175ab9..6cac620 100644
--- a/src/2021/2/mod.rs
+++ b/src/2021/2/mod.rs
@@ -1,31 +1,60 @@
-pub fn part1() -> anyhow::Result<i64> {
- let mut horizontal = 0;
- let mut vertical = 0;
- for line in data_lines!()? {
+pub enum Command {
+ Forward(i64),
+ Down(i64),
+ Up(i64),
+}
+
+pub fn parse(
+ fh: std::fs::File,
+) -> anyhow::Result<impl Iterator<Item = Command>> {
+ Ok(crate::util::parse::lines(fh).map(|line| {
if let Some(n) = line.strip_prefix("forward ") {
- horizontal += n.parse::<i64>()?;
+ Command::Forward(n.parse().unwrap())
} else if let Some(n) = line.strip_prefix("down ") {
- vertical += n.parse::<i64>()?;
+ Command::Down(n.parse().unwrap())
} else if let Some(n) = line.strip_prefix("up ") {
- vertical -= n.parse::<i64>()?;
+ Command::Up(n.parse().unwrap())
+ } else {
+ panic!("couldn't parse line: {}", line);
+ }
+ }))
+}
+
+pub fn part1(commands: impl Iterator<Item = Command>) -> anyhow::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() -> anyhow::Result<i64> {
+pub fn part2(commands: impl Iterator<Item = Command>) -> anyhow::Result<i64> {
let mut aim = 0;
let mut horizontal = 0;
let mut vertical = 0;
- for line in data_lines!()? {
- if let Some(n) = line.strip_prefix("forward ") {
- let x = n.parse::<i64>()?;
- horizontal += x;
- vertical += aim * x;
- } else if let Some(n) = line.strip_prefix("down ") {
- aim += n.parse::<i64>()?;
- } else if let Some(n) = line.strip_prefix("up ") {
- aim -= n.parse::<i64>()?;
+ 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)
@@ -33,6 +62,12 @@ pub fn part2() -> anyhow::Result<i64> {
#[test]
fn test() {
- assert_eq!(part1().unwrap(), 1694130);
- assert_eq!(part2().unwrap(), 1698850445);
+ assert_eq!(
+ part1(parse(crate::util::data(2021, 2).unwrap()).unwrap()).unwrap(),
+ 1694130
+ );
+ assert_eq!(
+ part2(parse(crate::util::data(2021, 2).unwrap()).unwrap()).unwrap(),
+ 1698850445
+ );
}