AoC2021/src/bin/day2.rs

38 lines
1001 B
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 pos = moves.iter().fold((0, 0, 0), |(x, y, aim), (mx, maim)| {
(x + mx, y + mx * (maim + aim), aim + maim)
});
println!("Answer2: {}", pos.0 * pos.1);
Ok(())
}