Skip to content

Commit

Permalink
faster parsing of day 18 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
kcaffrey committed Dec 18, 2023
1 parent 1a13550 commit 2a5b20a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www.
| [Day 15](./src/bin/15.rs) | `20.4µs` | `85.9µs` |
| [Day 16](./src/bin/16.rs) | `58.3µs` | `1.7ms` |
| [Day 17](./src/bin/17.rs) | `1.6ms` | `3.7ms` |
| [Day 18](./src/bin/18.rs) | `8.2µs` | `6.7µs` |
| [Day 18](./src/bin/18.rs) | `8.2µs` | `2.2µs` |

**Total: 14.09ms**
**Total: 14.08ms**
<!--- benchmarking table --->

---
Expand Down
32 changes: 31 additions & 1 deletion src/bin/18.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub fn part_one(input: &str) -> Option<i64> {
}

pub fn part_two(input: &str) -> Option<i64> {
Some(solve(input, parse_part2))
Some(solve_part2(input))
}

fn solve<F: Fn(&[u8]) -> (Direction, i64)>(input: &str, parser: F) -> i64 {
Expand All @@ -27,6 +27,36 @@ fn solve<F: Fn(&[u8]) -> (Direction, i64)>(input: &str, parser: F) -> i64 {
area + border_points / 2 + 1
}

fn solve_part2(input: &str) -> i64 {
let input = input.as_bytes();
let mut border_points = 0;
let mut area = 0;
let mut prev = Point::new(0, 0);
let mut index = 6;
while index < input.len() - 1 {
if input[index] == b'#' {
index += 1;
}
let distance: i64 = input[index..index + 5].iter().fold(0, |acc, &ch| {
let d = if ch < b'a' { ch - b'0' } else { ch - b'a' + 10 };
(acc << 4) + (d as i64)
});
let next = match input[index + 5] {
b'0' => Point::new(prev.x + distance, prev.y),
b'1' => Point::new(prev.x, prev.y + distance),
b'2' => Point::new(prev.x - distance, prev.y),
b'3' => Point::new(prev.x, prev.y - distance),
_ => unreachable!(),
};
index += 14;
area += prev.x * next.y - prev.y * next.x;
border_points += distance;
prev = next;
}
area = area.abs() / 2;
area + border_points / 2 + 1
}

fn parse_part1(line: &[u8]) -> (Direction, i64) {
let dir: Direction = line[0].try_into().expect("valid direction");
let distance = line[2..]
Expand Down

0 comments on commit 2a5b20a

Please sign in to comment.