[rs] Solve 2022_09 part 1
This commit is contained in:
parent
c1ff5e8157
commit
25d4e0298d
7 changed files with 2075 additions and 0 deletions
|
|
@ -48,6 +48,7 @@ days! {
|
|||
Y2022D06: "2022_06",
|
||||
Y2022D07: "2022_07",
|
||||
Y2022D08: "2022_08",
|
||||
Y2022D09: "2022_09",
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
|
|
@ -79,6 +80,7 @@ fn main() -> io::Result<()> {
|
|||
Day::Y2022D06 => y2022::d06::solve(input),
|
||||
Day::Y2022D07 => y2022::d07::solve(input),
|
||||
Day::Y2022D08 => y2022::d08::solve(input),
|
||||
Day::Y2022D09 => y2022::d09::solve(input),
|
||||
}
|
||||
eprintln!()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,3 +6,4 @@ pub mod d05;
|
|||
pub mod d06;
|
||||
pub mod d07;
|
||||
pub mod d08;
|
||||
pub mod d09;
|
||||
|
|
|
|||
60
rs/src/y2022/d09.rs
Normal file
60
rs/src/y2022/d09.rs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
use std::collections::HashSet;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Direction {
|
||||
Left,
|
||||
Right,
|
||||
Down,
|
||||
Up,
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
fn from_str(s: &str) -> Option<Self> {
|
||||
match s {
|
||||
"L" => Some(Self::Left),
|
||||
"R" => Some(Self::Right),
|
||||
"D" => Some(Self::Down),
|
||||
"U" => Some(Self::Up),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn move_head(self, head: (i32, i32)) -> (i32, i32) {
|
||||
match self {
|
||||
Self::Left => (head.0 - 1, head.1),
|
||||
Self::Right => (head.0 + 1, head.1),
|
||||
Self::Down => (head.0, head.1 - 1),
|
||||
Self::Up => (head.0, head.1 + 1),
|
||||
}
|
||||
}
|
||||
|
||||
fn move_tail(self, anchor: (i32, i32), tail: (i32, i32)) -> (i32, i32) {
|
||||
match self {
|
||||
Self::Left if tail.0 > anchor.0 + 1 => (anchor.0 + 1, anchor.1),
|
||||
Self::Right if tail.0 < anchor.0 - 1 => (anchor.0 - 1, anchor.1),
|
||||
Self::Down if tail.1 > anchor.1 + 1 => (anchor.0, anchor.1 + 1),
|
||||
Self::Up if tail.1 < anchor.1 - 1 => (anchor.0, anchor.1 - 1),
|
||||
_ => tail,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn solve(input: String) {
|
||||
// +x points right, +y points up
|
||||
let mut head = (0, 0);
|
||||
let mut tail = (0, 0);
|
||||
let mut tail_trail = HashSet::new();
|
||||
|
||||
for line in input.lines() {
|
||||
let (dir, amount) = line.split_once(' ').unwrap();
|
||||
let dir = Direction::from_str(dir).unwrap();
|
||||
let amount = amount.parse::<i32>().unwrap();
|
||||
for _ in 0..amount {
|
||||
head = dir.move_head(head);
|
||||
tail = dir.move_tail(head, tail);
|
||||
tail_trail.insert(tail);
|
||||
}
|
||||
}
|
||||
|
||||
println!("Part 1: {}", tail_trail.len());
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue