From c6379cd6b32da51f53a10f1e3d0d4ea7a31b0a27 Mon Sep 17 00:00:00 2001 From: Benjamin Wuethrich Date: Tue, 10 Dec 2024 23:05:30 -0500 Subject: [PATCH] Compute indexes instead of iterating --- 2024/day09/day09a | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/2024/day09/day09a b/2024/day09/day09a index b2742e49..a4955723 100755 --- a/2024/day09/day09a +++ b/2024/day09/day09a @@ -7,20 +7,25 @@ id = 0 disk_map.chars.map(&:to_i).each_with_index do |n, idx| if idx.even? - expanded << [id] * n + expanded.concat([id] * n) id += 1 else - expanded << ["."] * n + expanded.concat(["."] * n) end end -expanded.flatten! +empty_slots = expanded.each_with_index + .select { |block, _| block == "." } + .map { |_, idx| idx } -loop do - empty_idx = expanded.index(".") - block_idx = expanded.rindex { _1 != "." } - break unless empty_idx < block_idx - expanded[empty_idx], expanded[block_idx] = expanded[block_idx], expanded[empty_idx] +block_slots = expanded.each_with_index + .reject { |block, _| block == "." } + .map { |_, idx| idx } + .reverse + +empty_slots.each_with_index do |expanded_idx, idx| + break if expanded_idx > block_slots[idx] + expanded[expanded_idx], expanded[block_slots[idx]] = expanded[block_slots[idx]], expanded[expanded_idx] end checksum = 0