Solution day 2
parent
88dd4fe6a7
commit
da050ab5da
File diff suppressed because it is too large
Load Diff
|
@ -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)
|
||||
}
|
|
@ -1 +1,2 @@
|
|||
pub mod day_1;
|
||||
pub mod day_2;
|
||||
|
|
|
@ -4,4 +4,6 @@ fn main() {
|
|||
// Day 1
|
||||
println!("Day 1, part 1: {}", days::day_1::part1().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());
|
||||
}
|
||||
|
|
Reference in New Issue