advent-of-code/02-dive!/src/main.rs
Daniel Savory f897bd29e3 02-dive
2022-11-11 12:57:33 +11:00

38 lines
1.1 KiB
Rust

#![allow(dead_code, unused_imports)]
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
fn main() {
let mut h = 0;
let mut v = 0;
let mut aim = 0;
if let Ok(lines) = read_lines("directions.txt") {
for line in lines {
if let Ok(val) = line {
println!("{}", val);
//shadow assignment
let val: Vec<&str> = val.split(' ').collect();
let cmd = val[0];
let n = val[1].parse::<u32>().unwrap();
match cmd {
"forward" => {
h += n;
v += n * aim
}
"down" => aim += n,
"up" => aim -= n,
_ => println!("not a command"),
}
}
}
}
println!("h: {}, v: {}, final position: {}", h, v, h * v);
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}