summaryrefslogtreecommitdiff
path: root/day2/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'day2/src/main.rs')
-rw-r--r--day2/src/main.rs50
1 files changed, 50 insertions, 0 deletions
diff --git a/day2/src/main.rs b/day2/src/main.rs
new file mode 100644
index 0000000..3748138
--- /dev/null
+++ b/day2/src/main.rs
@@ -0,0 +1,50 @@
1use std::fs;
2use std::path::Path;
3
4enum Cmd {
5 Forward(i32),
6 Depth(i32)
7}
8
9impl From<&str> for Cmd {
10 fn from(s: &str) -> Self {
11 let (cmd, amount) = s.split_once(' ').expect("Malformed input");
12 let amount = amount.parse().expect("Malformed input");
13 match cmd {
14 "down" => Cmd::Depth(amount),
15 "up" => Cmd::Depth(-amount),
16 "forward" => Cmd::Forward(amount),
17 _ => unreachable!("Malformed input")
18 }
19 }
20}
21
22fn ex1(route: &[Cmd]) {
23 let pos = route.iter().fold((0,0),
24 |(f,d),c| match c {
25 Cmd::Depth(a) => (f,d+a),
26 Cmd::Forward(a) => (f+a,d),
27 }
28 );
29 println!("Ex1: The result is {}", pos.0 * pos.1);
30}
31
32fn ex2(route: &[Cmd]) {
33 let pos = route.iter().fold((0,0,0),
34 |(a,f,d),c| match c {
35 Cmd::Depth(i) => (a+i,f,d),
36 Cmd::Forward(i) => (a,f+i,d+a*i),
37 }
38 );
39 println!("Ex2: The result is {}", pos.1 * pos.2);
40}
41
42/* AOC21 Day 2: https://adventofcode.com/2021/day/2 */
43fn main() {
44 let input = Path::new("resources").join("input.txt");
45 let content = fs::read_to_string(input).expect("Unable to read input file");
46 let route: Vec<Cmd> = content.lines().map( |l| Cmd::from(l)).collect();
47 ex1(&route);
48 ex2(&route);
49}
50