55 lines
1.2 KiB
Rust
55 lines
1.2 KiB
Rust
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)
|
|
}
|