changeset 14:dcc060e59c47

Replace "each… each…" with a reduce and a flat map
author IBBoard <dev@ibboard.co.uk>
date Sat, 09 Dec 2023 20:07:16 +0000
parents 7826431dbc4f
children 5c8d2d181b94
files day5b.rb
diffstat 1 files changed, 19 insertions(+), 23 deletions(-) [+]
line wrap: on
line diff
--- a/day5b.rb	Sat Dec 09 19:53:22 2023 +0000
+++ b/day5b.rb	Sat Dec 09 20:07:16 2023 +0000
@@ -37,31 +37,27 @@
 def map_with_override(mappings, inputs)
 	inputs.flat_map do |input|
 		processed = []
-		unprocessed = [input]
-		# This "each… each" seems messy, but otherwise we can accidentally skip values
-		# because we're editing as we iterate
-		mappings.ranges.each do |mapping|
-			unprocessed.each do |input_range|
-				if mapping.source_range.end <= input_range.begin or input_range.end <= mapping.source_range.begin
-					# Input is entirely outside the mapped range
-				elsif mapping.source_range.cover?(input_range)
-					# Input is inside the mapped range
-					processed << ((input_range.begin+mapping.offset)...(input_range.end+mapping.offset))
-					unprocessed.delete(input_range)
-				elsif input_range.begin < mapping.source_range.begin
-					# Input straddles the start
-					unprocessed.delete(input_range)
-					unprocessed << ((input_range.begin)...(mapping.source_range.begin))
-					processed << ((mapping.source_range.begin+mapping.offset)...(input_range.end+mapping.offset))
-				else
-					# Must straddle the end
-					unprocessed.delete(input_range)
-					processed << ((input_range.begin+mapping.offset)...(mapping.source_range.end+mapping.offset))
-					unprocessed << ((mapping.source_range.end)...(input_range.end))
-				end
+		reduced_unprocessed = mappings.ranges.reduce(input) do |unprocessed, mapping|
+			if unprocessed.nil?
+				nil
+			elsif mapping.source_range.end <= input_range.begin or input_range.end <= mapping.source_range.begin
+				# Input is entirely outside the mapped range
+				input_range
+			elsif mapping.source_range.cover?(input_range)
+				# Input is inside the mapped range
+				processed << ((input_range.begin+mapping.offset)...(input_range.end+mapping.offset))
+				nil
+			elsif input_range.begin < mapping.source_range.begin
+				# Input straddles the start
+				processed << ((mapping.source_range.begin+mapping.offset)...(input_range.end+mapping.offset))
+				(input_range.begin)...(mapping.source_range.begin)
+			else
+				# Must straddle the end
+				processed << ((input_range.begin+mapping.offset)...(mapping.source_range.end+mapping.offset))
+				(mapping.source_range.end)...(input_range.end)
 			end
 		end
-		processed + unprocessed
+		processed + reduced_unprocessed
 	end
 end