Add day 2

This commit is contained in:
kageru 2021-12-02 06:13:01 +01:00
parent b734f0c5af
commit 329be3f1c1
Signed by: kageru
GPG Key ID: 8282A2BEA4ADA3D2
2 changed files with 1071 additions and 0 deletions

1000
2021/inputs/day02 Normal file

File diff suppressed because it is too large Load Diff

71
2021/src/bin/day02.rs Normal file
View File

@ -0,0 +1,71 @@
#![feature(test)]
extern crate test;
use aoc2021::common::*;
#[derive(Debug, Clone, Copy)]
enum Movement {
Up(i64),
Down(i64),
Forward(i64),
}
type Parsed = Vec<Movement>;
fn read_input() -> String {
read_file(2)
}
fn parse_input(raw: &str) -> Parsed {
raw.lines()
.filter_map(|l| l.split_once(' '))
.map(|(dir, dist)| match dir {
"up" => Movement::Up(dist.parse().unwrap()),
"down" => Movement::Down(dist.parse().unwrap()),
"forward" => Movement::Forward(dist.parse().unwrap()),
_ => unreachable!(),
})
.collect()
}
fn part1(parsed: &Parsed) -> i64 {
let (depth, distance) = parsed.iter().fold((0, 0), |(depth, distance), &mov| match mov {
Movement::Up(x) => (depth - x, distance),
Movement::Down(x) => (depth + x, distance),
Movement::Forward(x) => (depth, distance + x),
});
depth * distance
}
fn part2(parsed: &Parsed) -> i64 {
let (depth, distance, _) = parsed.iter().fold((0, 0, 0), |(depth, distance, aim), &mov| match mov {
Movement::Up(x) => (depth, distance, aim - x),
Movement::Down(x) => (depth, distance, aim + x),
Movement::Forward(x) => (depth + aim * x, distance + x, aim),
});
depth * distance
}
fn main() {
let input = parse_input(&read_input());
println!("Part 1: {}", part1(&input));
println!("Part 2: {}", part2(&input));
}
#[cfg(test)]
mod tests {
use super::*;
use aoc2021::*;
const TEST_INPUT: &str = "forward 5
down 5
forward 8
up 3
down 8
forward 2";
test!(part1() == 150);
test!(part2() == 900);
bench!(part1() == 1698735);
bench!(part2() == 1594785890);
bench_input!(len == 1000);
}