Skip to content

Commit 3669226

Browse files
committed
Use binary search at day 19 part 2 to make it fast
1 parent cbe5199 commit 3669226

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

aoc-solver/src/y2024/day18.rs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ pub fn a_star(corrupted: &[Coords], start: Coords, end: Coords) -> Option<u32> {
9696
continue;
9797
}
9898

99-
let tentative_g = g.entry(position).or_default().saturating_add(1);
99+
let tentative_g = g.get(&position).unwrap_or(&0) + 1;
100100
let existing_g = g.get(&neighbour).unwrap_or(&u32::MAX);
101101

102102
if tentative_g < *existing_g {
@@ -137,15 +137,23 @@ impl Solution for Day18 {
137137
fn part_2(&self, input: &str) -> Result<String, AocError> {
138138
let corrupted = parse(input)?;
139139

140-
let mut t = 1024;
141140
let start = (0, 0);
142141
let end = (70, 70);
143142

144-
while a_star(&corrupted[0..t], start, end).is_some() {
145-
t += 1;
143+
let mut low = 1024;
144+
let mut high = corrupted.len();
145+
146+
while low < high {
147+
let mid = (low + high) / 2;
148+
149+
if a_star(&corrupted[0..mid], start, end).is_some() {
150+
low = mid + 1;
151+
} else {
152+
high = mid;
153+
}
146154
}
147155

148-
Ok(format!("{},{}", corrupted[t - 1].0, corrupted[t - 1].1))
156+
Ok(format!("{},{}", corrupted[low - 1].0, corrupted[low - 1].1))
149157
}
150158
}
151159

0 commit comments

Comments
 (0)