-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
55 lines (48 loc) · 1.73 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use std::str::FromStr;
const FILE_PATH: &str = "input.txt";
#[derive(Debug, Copy, Clone)]
pub enum MoveDirection {
Forward(u32),
Down(u32),
Up(u32),
}
impl FromStr for MoveDirection {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (action, value) = s
.split_once(' ')
.ok_or(format!("Wrong format: `{}` cannot be parsed", s))?;
let value = value.parse::<u32>().map_err(|e| e.to_string())?;
match action {
"down" => Ok(Self::Down(value)),
"forward" => Ok(Self::Forward(value)),
"up" => Ok(Self::Up(value)),
_ => Err(format!("Wrong direction: {}", s)),
}
}
}
fn part_1(directions: impl Iterator<Item = MoveDirection>) {
let (x, y) = directions.fold((0, 0), |(x, y), dir| match dir {
MoveDirection::Forward(v) => (x + v, y),
MoveDirection::Down(v) => (x, y + v),
MoveDirection::Up(v) => (x, y.saturating_sub(v)),
});
println!("Part 1. Final pos = ({}, {}), Result = {}", x, y, x * y);
}
fn part_2(directions: impl Iterator<Item = MoveDirection>) {
let (x, y, _aim) = directions.fold((0, 0, 0), |(x, y, aim), dir| match dir {
MoveDirection::Forward(v) => (x + v, y + aim * v, aim),
MoveDirection::Down(v) => (x, y, aim + v),
MoveDirection::Up(v) => (x, y, aim.saturating_sub(v)),
});
println!("Part 2. Final pos = ({}, {}), Result = {}", x, y, x * y);
}
fn main() {
let file_content: Vec<MoveDirection> = std::fs::read_to_string(FILE_PATH)
.unwrap()
.split('\n')
.map(|str| MoveDirection::from_str(str).unwrap())
.collect();
part_1(file_content.iter().copied());
part_2(file_content.into_iter());
}