summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTom Smeding <tom.smeding@gmail.com>2018-12-13 19:31:25 +0100
committerTom Smeding <tom.smeding@gmail.com>2018-12-13 19:31:25 +0100
commita443f736c77bf14240b6ec0c8e5c8c21447074c4 (patch)
tree262b06d8a7178b1666cc6356ef6527092191728a
parentf1237b2dbfdd5940ea6474581574be64d818d355 (diff)
Day 13 part 2
-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))
}