From fff824749461ec0b0badc0027d31f3a9fc61e6e3 Mon Sep 17 00:00:00 2001 From: Kevin Caffrey Date: Thu, 14 Dec 2023 21:51:16 -0500 Subject: [PATCH] somehow this is faster and I don't understand fully why. I guess avoiding a branch that wrecks branch prediction? --- README.md | 4 ++-- src/bin/14.rs | 18 ++++++------------ 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index db5f86b..d3e47d2 100644 --- a/README.md +++ b/README.md @@ -43,9 +43,9 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www. | [Day 11](./src/bin/11.rs) | `16.3µs` | `15.7µs` | | [Day 12](./src/bin/12.rs) | `137.9µs` | `618.3µs` | | [Day 13](./src/bin/13.rs) | `12.3µs` | `15.9µs` | -| [Day 14](./src/bin/14.rs) | `24.4µs` | `10.7ms` | +| [Day 14](./src/bin/14.rs) | `26.7µs` | `5.5ms` | -**Total: 13.11ms** +**Total: 7.91ms** --- diff --git a/src/bin/14.rs b/src/bin/14.rs index 12d6a0a..02b654e 100644 --- a/src/bin/14.rs +++ b/src/bin/14.rs @@ -61,7 +61,6 @@ struct Platform { height: u8, round_rocks: Vec, distance_to_cubed_rocks: Vec>, - rock_stacks: Vec>, iteration: u16, } @@ -101,11 +100,9 @@ impl Platform { }; } } - let rock_stacks = vec![vec![RockStack::default(); grid[0].len()]; grid.len()]; Self { round_rocks, distance_to_cubed_rocks, - rock_stacks, iteration: 0, width, height, @@ -127,25 +124,22 @@ impl Platform { fn tilt(&mut self, dir: Direction) { self.iteration += 1; + let mut stacks = vec![vec![0; self.width as usize]; self.height as usize]; for rock in &mut self.round_rocks { let distance = self.distance_to_cubed_rocks[rock.row as usize][rock.col as usize].get(dir); let cubed_rock = rock .move_in_dir(dir, distance) .limit_to(self.height - 1, self.width - 1); - let stack = &mut self.rock_stacks[cubed_rock.row as usize][cubed_rock.col as usize]; - if stack.iteration != self.iteration { - stack.iteration = self.iteration; - stack.count = 0; - } - if stack.count > distance - 1 { - let total_move_distance = stack.count - distance + 1; + let stack = &mut stacks[cubed_rock.row as usize][cubed_rock.col as usize]; + if *stack > distance - 1 { + let total_move_distance = *stack - distance + 1; *rock = rock.move_in_dir(dir.rev(), total_move_distance); } else { - let total_move_distance = distance - 1 - stack.count; + let total_move_distance = distance - 1 - *stack; *rock = rock.move_in_dir(dir, total_move_distance); } - stack.count += 1; + *stack += 1; } }