From b4feda39f3e8e7c73b98828c0c56accaf79ee437 Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Tue, 10 Dec 2024 00:20:40 +0100 Subject: [PATCH] Remove free space objects when no more free space : improve part2 speed from 10ms to 7ms. --- src/day09.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/day09.rs b/src/day09.rs index eac0b8c..31a23cd 100644 --- a/src/day09.rs +++ b/src/day09.rs @@ -90,7 +90,8 @@ pub fn defrag_v2(mut memory: Vec) -> Vec { } for f in files.iter().rev() { - for free_space in free_spaces.iter_mut() { + for i in 0..free_spaces.len() { + let free_space = &mut free_spaces[i]; // Files are only move backward. if free_space.pos >= f.pos { break; @@ -100,7 +101,11 @@ pub fn defrag_v2(mut memory: Vec) -> Vec { memory[free_space.pos..free_space.pos + f.size].fill(v); memory[f.pos..f.pos + f.size].fill(EMPTY); free_space.size -= f.size; - free_space.pos += f.size; + if free_space.size == 0 { + free_spaces.remove(i); + } else { + free_space.pos += f.size; + } break; } } -- 2.45.2