aoc2021/src/day02.rs

52 lines
1.1 KiB
Rust

const INPUT: &str = include_str!("../inputs/02");
fn get_instructions() -> impl Iterator<Item = (&'static str, isize)> {
INPUT
.lines()
.filter_map(|s| s.split_once(' '))
.filter_map(|(op, n)| n.parse::<isize>().ok().map(|n| (op, n)))
}
fn part_1() -> isize {
let x: isize = get_instructions()
.filter(|(op, _)| *op == "forward")
.map(|(_, n)| n)
.sum();
let y: isize = get_instructions()
.filter_map(|(op, n)| match op {
"up" => Some(-n),
"down" => Some(n),
_ => None,
})
.sum();
x * y
}
fn part_2() -> isize {
let mut x = 0isize;
let mut depth = 0isize;
let mut aim = 0isize;
for (op, n) in get_instructions() {
match op {
"forward" => {
x += n;
depth += n * aim;
}
"down" => aim += n,
"up" => aim -= n,
_ => unreachable!(),
}
}
x * depth
}
pub fn main() {
println!("Day 2:");
println!(" Part 1: {}", part_1());
println!(" Part 2: {}", part_2());
}