Solution day 2

master
Jef Roosens 2021-12-02 14:58:41 +01:00
parent 88dd4fe6a7
commit da050ab5da
Signed by: Jef Roosens
GPG Key ID: B580B976584B5F30
4 changed files with 1057 additions and 0 deletions

1000
input/day2 100644

File diff suppressed because it is too large Load Diff

54
src/days/day_2.rs 100644
View File

@ -0,0 +1,54 @@
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::io::BufReader;
/// Parses a string & returns its effect on the horizontal & vertical position/aim
pub fn parse_ins(s: &str) -> (i32, i32) {
let mut parts = s.split_ascii_whitespace();
let command = parts.next().unwrap();
let num: i32 = parts.next().unwrap().parse().unwrap();
match command {
"forward" => (num, 0),
"down" => (0, num),
"up" => (0, -num),
_ => unimplemented!(),
}
}
pub fn part1() -> io::Result<i32> {
let file = File::open("input/day2")?;
let reader = BufReader::new(file);
let mut forward = 0;
let mut depth = 0;
for line in reader.lines() {
let (f, d) = parse_ins(&line.unwrap());
forward += f;
depth += d;
}
Ok(forward * depth)
}
pub fn part2() -> io::Result<i32> {
let file = File::open("input/day2")?;
let reader = BufReader::new(file);
let mut forward = 0;
let mut depth = 0;
let mut aim = 0;
for line in reader.lines() {
let (f, a) = parse_ins(&line.unwrap());
aim += a;
forward += f;
depth += aim * f;
}
Ok(forward * depth)
}

View File

@ -1 +1,2 @@
pub mod day_1; pub mod day_1;
pub mod day_2;

View File

@ -4,4 +4,6 @@ fn main() {
// Day 1 // Day 1
println!("Day 1, part 1: {}", days::day_1::part1().unwrap()); println!("Day 1, part 1: {}", days::day_1::part1().unwrap());
println!("Day 1, part 2: {}", days::day_1::part2().unwrap()); println!("Day 1, part 2: {}", days::day_1::part2().unwrap());
println!("Day 2, part 1: {}", days::day_2::part1().unwrap());
println!("Day 2, part 2: {}", days::day_2::part2().unwrap());
} }