This commit is contained in:
Zoé Cassiopée Gauthier 2021-12-02 09:49:53 -05:00
parent 511477ed3d
commit d36f150d2c
4 changed files with 1071 additions and 4 deletions

View File

@ -6,3 +6,7 @@ edition = "2021"
[[bin]] [[bin]]
name = "day1" name = "day1"
path = "src/day1.rs" path = "src/day1.rs"
[[bin]]
name = "day2"
path = "src/day2.rs"

1000
inputs/day2.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -18,10 +18,7 @@ fn main() {
.collect(); .collect();
println!("increased {} times", increases(&measurements)); println!("increased {} times", increases(&measurements));
println!( println!("increased {} times", increases(&convolve(&measurements)));
"increased {} times",
increases(&convolve(&measurements))
);
} }
#[test] #[test]

66
src/day2.rs Normal file
View File

@ -0,0 +1,66 @@
use std::io::{self, BufRead};
use std::num::ParseIntError;
use std::str::FromStr;
enum Action {
Forward,
Down,
Up,
}
struct Command {
action: Action,
units: usize,
}
impl FromStr for Command {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Command, Self::Err> {
let words = s.split_once(' ').unwrap();
let action = match words.0 {
"forward" => Ok(Action::Forward),
"down" => Ok(Action::Down),
"up" => Ok(Action::Up),
_ => Err(()),
};
let units = words.1.parse()?;
Ok(Command {
action: action.unwrap(),
units: units,
})
}
}
fn main() {
const INPUT: &'static str = include_str!("../inputs/day2.txt");
let commands: Vec<Command> = io::Cursor::new(INPUT)
.lines()
.map(|l| l.unwrap().parse().unwrap())
.collect();
let mut position = 0;
let mut depth = 0;
let mut aim = 0;
for command in commands {
match command.action {
Action::Forward => {
position += command.units;
depth += aim * command.units;
}
Action::Down => {
aim += command.units;
}
Action::Up => {
aim -= command.units;
}
}
}
println!(
"horizontal position {}, depth {}, aim {}",
position, depth, aim
);
println!("solution {}", position * depth);
}