From c739a665d3b72214797f8d865669443aa186e8ff Mon Sep 17 00:00:00 2001 From: Ishan Jain Date: Fri, 9 Dec 2022 19:57:57 +0530 Subject: [PATCH] Optimized day 9 part 2 by not inserting tail position if it hasn't changed --- src/main.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index 269e367..1ec4a62 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,8 @@ #![feature(byte_slice_trim_ascii)] #![feature(test)] +extern crate test; use std::collections::HashSet; -extern crate test; const INPUTS: [&[u8]; 2] = [ include_bytes!("../inputs/sample.txt"), @@ -48,7 +48,8 @@ fn main() { fn solution(input: Vec) -> usize { let mut locs = [(0, 0); 10]; - let mut set: HashSet<(i32, i32)> = HashSet::with_capacity(3000); + let mut set: HashSet<(i32, i32)> = HashSet::with_capacity_and_hasher(3000, Default::default()); + set.insert((0, 0)); for mmove in input { let (steps, (dsxh, dsyh)) = match mmove { @@ -58,6 +59,8 @@ fn solution(input: Vec) -> usize { Move::D(v) => (v, (0, 1)), }; + let locs9 = locs[9]; + for _ in 0..steps { // Update Head position locs[0].0 += dsxh; @@ -72,7 +75,9 @@ fn solution(input: Vec) -> usize { locs[i] = loci; } - set.insert(locs[9]); + if locs9 != locs[9] { + set.insert(locs[9]); + } } }