From 21dfc7f6309b76c8adff7baf52f0b6c9984c41e9 Mon Sep 17 00:00:00 2001 From: Johannes Date: Tue, 25 Dec 2018 14:32:32 +0100 Subject: [PATCH] day22 little speed improvement --- src/tasks/day22.rs | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/src/tasks/day22.rs b/src/tasks/day22.rs index 73e8c5f..e6a7a2f 100644 --- a/src/tasks/day22.rs +++ b/src/tasks/day22.rs @@ -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 = BinaryHeap::new(); let mut distances: HashMap = 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; }