Skip to content

Commit

Permalink
somehow this is faster and I don't understand fully why. I guess avoi…
Browse files Browse the repository at this point in the history
…ding a branch that wrecks branch prediction?
  • Loading branch information
kcaffrey committed Dec 15, 2023
1 parent 210ec6e commit fff8247
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 14 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
<!--- benchmarking table --->

---
Expand Down
18 changes: 6 additions & 12 deletions src/bin/14.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ struct Platform {
height: u8,
round_rocks: Vec<Coordinate>,
distance_to_cubed_rocks: Vec<Vec<CachedDistance>>,
rock_stacks: Vec<Vec<RockStack>>,
iteration: u16,
}

Expand Down Expand Up @@ -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,
Expand All @@ -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;
}
}

Expand Down

0 comments on commit fff8247

Please sign in to comment.