Day 2
This commit is contained in:
parent
4d6e7dcf92
commit
7c9e4a2da1
3 changed files with 1065 additions and 0 deletions
6
input/02-test.txt
Normal file
6
input/02-test.txt
Normal file
|
@ -0,0 +1,6 @@
|
|||
forward 5
|
||||
down 5
|
||||
forward 8
|
||||
up 3
|
||||
down 8
|
||||
forward 2
|
1000
input/02.txt
Normal file
1000
input/02.txt
Normal file
File diff suppressed because it is too large
Load diff
59
src/bin/02.rs
Normal file
59
src/bin/02.rs
Normal file
|
@ -0,0 +1,59 @@
|
|||
fn main() {
|
||||
let mut pos = State::default();
|
||||
pos.apply(input());
|
||||
println!("First solution: {:?} => {}", pos, pos.position * pos.depth);
|
||||
|
||||
let mut pos = State::default();
|
||||
pos.apply_new(input());
|
||||
println!("Second solution: {:?} => {}", pos, pos.position * pos.depth);
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct State {
|
||||
position: i32,
|
||||
depth: i32,
|
||||
aim: i32,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn apply(&mut self, instructions: impl Iterator<Item = Instruction>) {
|
||||
for i in instructions {
|
||||
match i.direction {
|
||||
"up" => self.depth -= i.distance,
|
||||
"down" => self.depth += i.distance,
|
||||
"forward" => self.position += i.distance,
|
||||
d => panic!("unknown direction: {}", d),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_new(&mut self, instructions: impl Iterator<Item = Instruction>) {
|
||||
for i in instructions {
|
||||
match i.direction {
|
||||
"up" => self.aim -= i.distance,
|
||||
"down" => self.aim += i.distance,
|
||||
"forward" => {
|
||||
self.position += i.distance;
|
||||
self.depth += self.aim * i.distance;
|
||||
}
|
||||
d => panic!("unknown direction: {}", d),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Instruction {
|
||||
direction: &'static str,
|
||||
distance: i32,
|
||||
}
|
||||
|
||||
fn input() -> impl Iterator<Item = Instruction> {
|
||||
include_str!("../../input/02.txt")
|
||||
.lines()
|
||||
.filter_map(|l| l.split_once(" "))
|
||||
.map(|(d, n)| Instruction {
|
||||
direction: d,
|
||||
distance: n.parse().unwrap(),
|
||||
})
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue