day22 little speed improvement

This commit is contained in:
Johannes
2018-12-25 14:32:32 +01:00
parent 719db128cf
commit 21dfc7f630

View File

@@ -7,13 +7,14 @@ use std::time::Instant;
pub fn both() {
let start = Instant::now();
let mut cave = Cave::create(3879, Node(8, 713, Torch));
println!("{:?}", Instant::now() - start);
let start = Instant::now();
println!("#{:?}", Instant::now() - start);
let x = Instant::now();
println!("Sum of erosion indexes: {}", cave.erosion_sum());
println!("{:?}", Instant::now() - start);
let start = Instant::now();
println!("#{:?}", Instant::now() - x);
let x = Instant::now();
println!("Shortest path length: {}", cave.shortest_path_length());
println!("{:?}", Instant::now() - start);
println!("#{:?}", Instant::now() - x);
println!("#Overall run time: {:?}", Instant::now() - start);
}
#[derive(PartialEq, Clone, Copy, Debug, Eq, Hash)]
@@ -37,7 +38,8 @@ impl Cave {
if target.2 != Torch {
panic!("A valid target point needs the torch equipped");
}
let map = HashMap::with_capacity(target.0 * target.1);
let map = HashMap::with_capacity((target.0 + 1) * (target.1 + 1));
Cave { map, target, depth }
}
@@ -74,9 +76,17 @@ impl Cave {
}
fn shortest_path_length(&mut self) -> usize {
self.map.reserve(
std::cmp::max(self.target.0, self.target.1)
* std::cmp::max(self.target.0, self.target.1)
- self.map.len(),
);
let start = Node(0, 0, Torch);
let mut open: BinaryHeap<State> = BinaryHeap::new();
let mut distances: HashMap<Node, usize> = HashMap::new();
// let mut rightmost = 0;
// let mut lowest = 0;
// let mut visited_counter = 0;
distances.insert(start, 0);
open.push(State {
@@ -86,8 +96,20 @@ impl Cave {
// Examine the frontier with lower cost nodes first (min-heap)
while let Some(State { cost, position }) = open.pop() {
// if position.0 > rightmost {
// rightmost = position.0;
// }
// if position.1 > lowest {
// lowest = position.1;
// }
// visited_counter += 1;
// Alternatively we could have continued to find all shortest paths
if position == self.target {
// println!(
// "Visited {} nodes ({}, {})",
// visited_counter, rightmost, lowest
// );
return cost;
}