Day 9 done

This commit is contained in:
Dylan "smellyfis" Thies
2022-12-19 10:09:28 -05:00
parent ea8464aad6
commit e8a9a65d71
3 changed files with 36 additions and 51 deletions

View File

@@ -1,4 +1,4 @@
use itertools::Itertools;
use std::collections::HashSet;
use std::fs::File;
use std::io::{prelude::*, BufReader};
@@ -7,8 +7,13 @@ fn main() -> std::io::Result<()> {
let file = File::open("input")?;
let reader = BufReader::new(file);
let mut tail_pos: Vec<(i32, i32)> = vec![(0, 0)];
let mut head_pos: Vec<(i32, i32)> = vec![(0, 0)];
let mut snake = vec![(0_i32, 0_i32); 10];
let mut visited: Vec<HashSet<(i32, i32)>> = vec![HashSet::new(); 10];
//intialize the visited
snake.iter().enumerate().for_each(|(i, x)| {
visited[i].insert(*x);
});
//read in input
reader.lines().for_each(|line| {
@@ -18,8 +23,7 @@ fn main() -> std::io::Result<()> {
_ => panic!("failed parseing line {}", line),
};
for _ in 0..steps {
let (mut cur_head_x, mut cur_head_y) = head_pos.last().unwrap();
let (mut cur_tail_x, mut cur_tail_y) = tail_pos.last().unwrap();
let (mut cur_head_x, mut cur_head_y) = snake[0];
match direction {
"L" => cur_head_x -= 1,
"R" => cur_head_x += 1,
@@ -27,37 +31,37 @@ fn main() -> std::io::Result<()> {
"D" => cur_head_y -= 1,
x => panic!("invalid movement {}", x),
};
let x_offset = cur_head_x - cur_tail_x;
let y_offset = cur_head_y - cur_tail_y;
if x_offset > 1 {
if y_offset != 0 {
cur_tail_y = cur_head_y;
let new_head_pos = (cur_head_x, cur_head_y);
snake[0] = new_head_pos;
visited[0].insert(new_head_pos);
for i in 1..snake.len() {
let (cur_head_x, cur_head_y) = snake[i - 1];
let mut new_pos = snake[i];
let (cur_tail_x, cur_tail_y) = new_pos;
let mut x_offset = cur_head_x - cur_tail_x;
let mut y_offset = cur_head_y - cur_tail_y;
if std::cmp::max(x_offset.abs(), y_offset.abs()) > 1 {
if y_offset.abs() >= 2 && x_offset == 0 {
y_offset = y_offset.clamp(-1, 1);
} else if x_offset.abs() > 2 && y_offset == 0 {
x_offset = x_offset.clamp(-1, 1);
} else if x_offset.abs() > 1 || y_offset.abs() > 1 {
x_offset = x_offset.clamp(-1, 1);
y_offset = y_offset.clamp(-1, 1);
} else {
x_offset = 0;
y_offset = 0;
}
new_pos = (cur_tail_x + x_offset, cur_tail_y + y_offset);
}
cur_tail_x += 1
} else if x_offset < -1 {
if y_offset != 0 {
cur_tail_y = cur_head_y;
}
cur_tail_x -= 1
} else if y_offset > 1 {
if x_offset != 0 {
cur_tail_x = cur_head_x;
}
cur_tail_y += 1
} else if y_offset < -1 {
if x_offset != 0 {
cur_tail_x = cur_head_x;
}
cur_tail_y -= 1
snake[i] = new_pos;
visited[i].insert(new_pos);
}
let new_tail = (cur_tail_x, cur_tail_y);
if *tail_pos.last().unwrap() != new_tail {
tail_pos.push(new_tail);
}
head_pos.push((cur_head_x, cur_head_y));
}
});
let part1 = tail_pos.iter().unique().count();
let part1 = visited[1].len();
println!("Part 1: {}", part1);
let part2 = visited[9].len();
println!("Part 2: {}", part2);
Ok(())
}