Skip to content

Instantly share code, notes, and snippets.

@0e4ef622
Last active December 13, 2018 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0e4ef622/e449fd5e71e7168c4f9eb8e836d9bbf6 to your computer and use it in GitHub Desktop.
Save 0e4ef622/e449fd5e71e7168c4f9eb8e836d9bbf6 to your computer and use it in GitHub Desktop.
aoc day 13 2018
fn load(input: &str) -> (isize, isize, Vec<u8>, Vec<(isize, isize, isize, isize, usize)>) {
let width = input.lines().next().unwrap().len() as isize;
let height = input.lines().count() as isize;
let mut matrix = vec![0; (width*height) as usize];
let mut cars: Vec<(isize, isize, isize, isize, usize)> = vec![]; // (y, x, dx, dy, state) for sorting, down is positive
for (y, line) in input.lines().enumerate() {
for (x, &c) in line.as_bytes().iter().enumerate() {
let x = x as isize;
let y = y as isize;
matrix[(y*width+x) as usize] = c;
match c {
b'>' => cars.push((y, x, 1, 0, 0)),
b'v' => cars.push((y, x, 0, 1, 0)),
b'<' => cars.push((y, x, -1, 0, 0)),
b'^' => cars.push((y, x, 0, -1, 0)),
_ => (),
}
}
}
for c in &mut matrix {
match c {
b'>' | b'<' => *c = b'-',
b'v' | b'^' => *c = b'|',
_ => (),
}
}
(width, height, matrix, cars)
}
fn move_car(matrix: &[u8], width: isize, (y, x, dx, dy, state): &mut (isize, isize, isize, isize, usize)) {
*x += *dx;
*y += *dy;
match matrix[(*y*width+*x) as usize] {
b'\\' => {
let newdx = *dy;
let newdy = *dx;
*dx = newdx;
*dy = newdy;
}
b'/' => {
let newdx = -*dy;
let newdy = -*dx;
*dx = newdx;
*dy = newdy;
}
b'+' => {
match state {
0 => { // turn left
let newdx = *dy;
let newdy = -*dx;
*dx = newdx;
*dy = newdy;
}
1 => (),
2 => { // turn right
let newdx = -*dy;
let newdy = *dx;
*dx = newdx;
*dy = newdy;
}
_ => unreachable!(),
}
*state = (*state + 1) % 3;
}
_ => (),
}
}
pub fn part1(input: &str) -> (isize, isize) {
let (width, _height, matrix, mut cars) = load(input);
'l: loop {
cars.sort_unstable();
for i in 0..cars.len() {
let car = &mut cars[i];
move_car(&matrix, width, car);
let &mut (y, x, ..) = car;
// Look for cars that have the same position. These are collisions.
if cars
.iter()
.enumerate()
.filter(|v| v.0 != i)
.any(|(_, v)| v.0 == y && v.1 == x)
{
break 'l (x, y);
}
}
}
}
pub fn part2(input: &str) -> (isize, isize) {
let (width, _height, matrix, mut cars) = load(input);
'l: loop {
cars.sort_unstable();
let mut i = 0;
while i < cars.len() {
let car = &mut cars[i];
move_car(&matrix, width, car);
let &mut (y, x, ..) = car;
// Look for cars that have the same position. These are collisions.
if let Some((oi, _)) = cars
.iter()
.enumerate()
.filter(|v| v.0 != i)
.find(|(_, v)| v.0 == y && v.1 == x)
{
if oi < i {
cars.remove(i);
cars.remove(oi);
i -= 1;
} else {
cars.remove(oi);
cars.remove(i);
}
} else {
i += 1;
}
}
if cars.len() == 1 {
break 'l (cars[0].1, cars[0].0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment