day09: Add part 1

This commit is contained in:
MasterofJOKers 2022-12-24 14:29:57 +01:00
parent 2ffa87d872
commit ae6ac6979a
3 changed files with 98 additions and 0 deletions

7
day09/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day09"
version = "0.1.0"

8
day09/Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "day09"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

83
day09/src/main.rs Normal file
View File

@ -0,0 +1,83 @@
use std::collections::HashSet;
use std::error;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
const DEBUG: bool = false;
struct Pos {
x: i32,
y: i32
}
impl Pos {
// Move the position x into x direction and y into y direction
fn move_(&mut self, x: i32, y: i32) {
self.x += x;
self.y += y;
}
fn move_into_direction(&mut self, direction: &str) -> Result<(), Box<dyn error::Error>> {
match direction {
"R" => self.move_(1, 0),
"L" => self.move_(-1, 0),
"U" => self.move_(0, 1),
"D" => self.move_(0, -1),
_ => Err(format!("Unknown direction {direction}."))?
};
Ok(())
}
fn move_after(&mut self, other: &Pos) {
let x_diff = other.x - self.x;
let y_diff = other.y - self.y;
// no movement if we're close enough
if x_diff.abs() <= 1 && y_diff.abs() <= 1 {
return
}
if x_diff.abs() > y_diff.abs() {
self.move_((x_diff.abs() - 1) * x_diff.signum(), y_diff);
} else {
self.move_(x_diff, (y_diff.abs() - 1) * y_diff.signum());
}
}
fn show(&self) {
println!("x: {} y: {}", self.x, self.y)
}
}
fn main() -> Result<(), Box<dyn error::Error>> {
let f = File::open("input.txt")?;
let reader = BufReader::new(f);
let mut h_pos = Pos { x: 0, y: 0 };
let mut t_pos = Pos { x: 0, y: 0 };
let mut visited_locations = HashSet::new();
for line in reader.lines() {
let line = line?;
let mut s_iter = line.split_whitespace();
let direction = s_iter.next().ok_or(format!("Could not split {line} on whitespace"))?;
let amount: i32 = s_iter.next().ok_or(format!("Could not split {line} into 2 parts."))?.parse()?;
for _ in 0..amount {
h_pos.move_into_direction(direction)?;
t_pos.move_after(&h_pos);
if DEBUG {
h_pos.show();
t_pos.show();
}
visited_locations.insert((t_pos.x.to_owned(), t_pos.y.to_owned()));
}
if DEBUG {
println!("");
}
}
println!("Visited {} locations", visited_locations.len());
Ok(())
}