diff --git a/src/tasks/day13.rs b/src/tasks/day13.rs index 9ba5ef2..cfacc3a 100644 --- a/src/tasks/day13.rs +++ b/src/tasks/day13.rs @@ -1,8 +1,9 @@ use crate::utils; -use std::collections::HashSet; +use std::collections::HashMap; pub fn task1() { let (map, mut carts) = read_input(); + println!("We have {} carts initially", carts.len()); loop { perform_round(&map, &mut carts); } @@ -37,6 +38,7 @@ fn read_input() -> (Vec>, Vec) { y, direction: c, intersections_visited: 0, + active: true, }); } } @@ -46,11 +48,13 @@ fn read_input() -> (Vec>, Vec) { (map, carts) } +#[derive(Debug)] struct Cart { x: usize, y: usize, direction: char, intersections_visited: usize, + active: bool, } fn perform_round(map: &Vec>, carts: &mut Vec) { @@ -61,10 +65,19 @@ fn perform_round(map: &Vec>, carts: &mut Vec) { a.y.cmp(&b.y) } }); - let mut positions: HashSet<(usize, usize)> = - carts.iter().map(|cart| (cart.x, cart.y)).collect(); + let mut positions: HashMap<(usize, usize), usize> = carts + .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); match cart.direction { '>' => cart.x += 1, @@ -106,11 +119,30 @@ fn perform_round(map: &Vec>, carts: &mut Vec) { } (_, _) => cart.direction, }; - if positions.contains(&(cart.x, cart.y)) { - panic!("We have a collision at {},{}!", cart.x, cart.y); + if positions.contains_key(&(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 { 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) + ); + } }