AoC2021/src/bin/day2.rs

45 lines
1.1 KiB
Rust

use std::error::Error;
use std::fs::File;
use std::io::{self, BufRead};
use std::vec::Vec;
fn to_moves(line: String) -> (i32, i32) {
let mut parts = line.split(" ");
let dir = parts.nth(0).unwrap();
let arg: i32 = parts.nth(0).unwrap().parse().unwrap();
match dir {
"up" => (0, -arg),
"down" => (0, arg),
"forward" => (arg, 0),
_ => panic!("Unsupported Direction: {}", dir),
}
}
fn main() -> Result<(), Box<dyn Error>> {
let file = File::open("inputs/day2.txt")?;
let lines = io::BufReader::new(file).lines().map(|l| l.unwrap());
let moves: Vec<(i32, i32)> = lines.map(|l| to_moves(l)).collect();
let pos = moves
.iter()
.fold((0, 0), |(ax, ay), (bx, by)| (ax + bx, ay + by));
println!("Answer1: {}", pos.0 * pos.1);
let mut aim = 0;
let mut pos = (0, 0);
for m in moves.iter() {
aim = aim + m.1;
println!("{} {}", m.0, m.1);
pos = (pos.0 + m.0, pos.1 + m.0 * aim);
println!("{} {}", pos.0, pos.1);
}
println!("Answer2: {}", pos.0 * pos.1);
Ok(())
}