day13 part2

This commit is contained in:
Johannes
2018-12-16 01:37:37 +01:00
parent c1c761f2ba
commit 807bff7977

View File

@@ -1,8 +1,9 @@
use crate::utils; use crate::utils;
use std::collections::HashSet; use std::collections::HashMap;
pub fn task1() { pub fn task1() {
let (map, mut carts) = read_input(); let (map, mut carts) = read_input();
println!("We have {} carts initially", carts.len());
loop { loop {
perform_round(&map, &mut carts); perform_round(&map, &mut carts);
} }
@@ -37,6 +38,7 @@ fn read_input() -> (Vec<Vec<char>>, Vec<Cart>) {
y, y,
direction: c, direction: c,
intersections_visited: 0, intersections_visited: 0,
active: true,
}); });
} }
} }
@@ -46,11 +48,13 @@ fn read_input() -> (Vec<Vec<char>>, Vec<Cart>) {
(map, carts) (map, carts)
} }
#[derive(Debug)]
struct Cart { struct Cart {
x: usize, x: usize,
y: usize, y: usize,
direction: char, direction: char,
intersections_visited: usize, intersections_visited: usize,
active: bool,
} }
fn perform_round(map: &Vec<Vec<char>>, carts: &mut Vec<Cart>) { fn perform_round(map: &Vec<Vec<char>>, carts: &mut Vec<Cart>) {
@@ -61,10 +65,19 @@ fn perform_round(map: &Vec<Vec<char>>, carts: &mut Vec<Cart>) {
a.y.cmp(&b.y) a.y.cmp(&b.y)
} }
}); });
let mut positions: HashSet<(usize, usize)> = let mut positions: HashMap<(usize, usize), usize> = carts
carts.iter().map(|cart| (cart.x, cart.y)).collect(); .iter()
.enumerate()
.filter(|(_, cart)| cart.active)
.map(|(i, cart)| ((cart.x, cart.y), i))
.collect();
for cart_index in 0..carts.len() {
let mut cart = &mut carts[cart_index];
if !cart.active {
continue;
}
for cart in carts {
let pos_old = (cart.x, cart.y); let pos_old = (cart.x, cart.y);
match cart.direction { match cart.direction {
'>' => cart.x += 1, '>' => cart.x += 1,
@@ -106,11 +119,30 @@ fn perform_round(map: &Vec<Vec<char>>, carts: &mut Vec<Cart>) {
} }
(_, _) => cart.direction, (_, _) => cart.direction,
}; };
if positions.contains(&(cart.x, cart.y)) { if positions.contains_key(&(cart.x, cart.y)) {
panic!("We have a collision at {},{}!", cart.x, cart.y); // Task1: panic here with coordinates
println!("We have a collision at {},{}!", cart.x, cart.y);
let other_index = positions[&(cart.x, cart.y)];
cart.active = false;
if !carts[other_index].active {
panic!("that one crashed already before!");
}
carts[other_index].active = false;
positions.remove(&(carts[cart_index].x, carts[cart_index].y));
positions.remove(&pos_old);
println!(
"{} carts left",
carts.iter().filter(|cart| cart.active).count()
);
} else { } else {
positions.remove(&pos_old); positions.remove(&pos_old);
positions.insert((cart.x, cart.y)); positions.insert((cart.x, cart.y), cart_index);
} }
} }
if carts.iter().filter(|cart| cart.active).count() == 1 {
panic!(
"exactly one active cart left: {:?}",
carts.iter().find(|cart| cart.active)
);
}
} }