AoC2022/d09/src/a2.rs
2022-12-11 18:06:33 +01:00

83 lines
1.6 KiB
Rust

#[derive(Copy, Clone, PartialEq)]
struct Pos {
x :i32,
y :i32
}
fn move_tail(head :&Pos, tail :&mut Pos) {
let dx = head.x - tail.x;
let dy = head.y - tail.y;
if dx.abs() > 1 || dy.abs() > 1{
tail.x += dx.signum();
tail.y += dy.signum();
}
}
fn execute_move(head :&mut Pos, tails :&mut Vec<Pos>, cmd :&char) {
match cmd {
'U' => {
head.y += 1;
}
'D' => {
head.y -= 1;
}
'L' => {
head.x -= 1;
}
'R' => {
head.x += 1;
}
_ => {}
}
move_tail(head, &mut tails.first_mut().unwrap());
for i in 1..tails.len() {
move_tail(&tails[i-1].clone(), &mut tails[i]);
}
}
fn parse_command(inp :&String) -> (char, i32) {
let split = inp.split(' ').collect::<Vec<&str>>();
return (split[0].chars().nth(0).unwrap(), split[1].parse::<i32>().unwrap());
}
pub fn run(inp :Vec<String>) {
let mut visited_coordinates :Vec<Pos> = vec![];
let mut head_pos = Pos {x: 0, y: 0} ;
let mut tails :Vec<Pos> = vec![Pos {x: 0, y: 0}; 9];
visited_coordinates.push(head_pos.clone());
for curr_move in inp {
let commands = parse_command(&curr_move);
for _ in 0..commands.1 {
execute_move(&mut head_pos, &mut tails, &commands.0);
if !visited_coordinates.contains(&tails.last().unwrap()) {
visited_coordinates.push(tails.last().unwrap().clone());
}
}
}
println!("a2: {}", visited_coordinates.len());
}