aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--y2021/src/d02.rs35
-rw-r--r--y2021/src/lib.rs1
-rw-r--r--y2021/src/main.rs8
3 files changed, 43 insertions, 1 deletions
diff --git a/y2021/src/d02.rs b/y2021/src/d02.rs
new file mode 100644
index 0000000..f844106
--- /dev/null
+++ b/y2021/src/d02.rs
@@ -0,0 +1,35 @@
+
+pub fn part1<T: Iterator<Item = String>>(e: T) -> usize {
+ let (h, d) = e.fold((0, 0), |(h, d), l| {
+ let (td, tv) = l.split_once(" ").unwrap();
+ let tv = tv.parse::<usize>().unwrap();
+
+ match td {
+ "forward" => (h + tv, d),
+ "down" => (h, d + tv),
+ "up" => (h, d - tv),
+ _ => unreachable!(),
+ }
+ });
+
+ h * d
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ static EX: [&str; 6] = [
+ "forward 5",
+ "down 5",
+ "forward 8",
+ "up 3",
+ "down 8",
+ "forward 2",
+ ];
+
+ #[test]
+ fn test() {
+ assert_eq!(150, part1(EX.iter().map(|x| x.to_string())));
+ }
+}
diff --git a/y2021/src/lib.rs b/y2021/src/lib.rs
index 3f264b0..bb05a59 100644
--- a/y2021/src/lib.rs
+++ b/y2021/src/lib.rs
@@ -1,3 +1,4 @@
pub mod d01;
+pub mod d02;
pub mod utils;
diff --git a/y2021/src/main.rs b/y2021/src/main.rs
index d920269..4605cdd 100644
--- a/y2021/src/main.rs
+++ b/y2021/src/main.rs
@@ -1,6 +1,6 @@
use y2021:: {
- d01,
+ d01, d02,
utils::get_input_for_day,
};
@@ -20,4 +20,10 @@ fn main() {
let a = d01::part2(get_input_for_day(1));
println!("2021: day 1 part 2: {}", a);
}
+
+ // day 2
+ if args.is_empty() || args.contains("2") {
+ let a = d02::part1(get_input_for_day(2));
+ println!("2021: day 2 part 1: {}", a);
+ }
}