summaryrefslogtreecommitdiff
path: root/2018
diff options
context:
space:
mode:
Diffstat (limited to '2018')
-rw-r--r--2018/src/day13.rs47
1 files changed, 37 insertions, 10 deletions
diff --git a/2018/src/day13.rs b/2018/src/day13.rs
index 13ff3a4..92411c1 100644
--- a/2018/src/day13.rs
+++ b/2018/src/day13.rs
@@ -139,10 +139,18 @@ pub fn main<T: BufRead>(reader: T) -> io::Result<(String, String)> {
}
}
- let part1;
+ let mut first_crash = None;
+ let part2;
+
+ loop {
+ let mut to_remove = Vec::new();
+
+ for (i, mut cart) in carts.iter_mut().enumerate() {
+ if !hascart[cart.pos.y][cart.pos.x] {
+ to_remove.push(i);
+ continue;
+ }
- 'outer: loop {
- for mut cart in &mut carts {
let pos2 = cart.nextpos();
let c = grid[pos2.y][pos2.x];
@@ -156,15 +164,29 @@ pub fn main<T: BufRead>(reader: T) -> io::Result<(String, String)> {
dir2 = newdir(&cart.dir, c);
}
+ hascart[cart.pos.y][cart.pos.x] = false;
+
if hascart[pos2.y][pos2.x] {
- part1 = format!("{},{}", pos2.x, pos2.y);
- break 'outer;
+ if first_crash.is_none() {
+ first_crash = Some(pos2.clone());
+ }
+
+ to_remove.push(i);
+ hascart[pos2.y][pos2.x] = false;
+ } else {
+ hascart[pos2.y][pos2.x] = true;
+ cart.pos = pos2;
+ cart.dir = dir2;
}
+ }
- hascart[cart.pos.y][cart.pos.x] = false;
- hascart[pos2.y][pos2.x] = true;
- cart.pos = pos2;
- cart.dir = dir2;
+ for idx in to_remove {
+ carts.swap_remove(idx);
+ }
+
+ if carts.len() == 1 {
+ part2 = format!("{},{}", carts[0].pos.x, carts[0].pos.y);
+ break;
}
carts.sort_by_key(|cart| (cart.pos.y, cart.pos.x));
@@ -172,5 +194,10 @@ pub fn main<T: BufRead>(reader: T) -> io::Result<(String, String)> {
// print_grid(&grid, &carts);
}
- Ok((part1, String::new()))
+ let part1 = match first_crash {
+ Some(pos) => format!("{},{}", pos.x, pos.y),
+ None => unreachable!()
+ };
+
+ Ok((part1, part2))
}