From 729a8ff201c0ce527e434246a909ce78764aa68a Mon Sep 17 00:00:00 2001 From: "Andrew R. M" Date: Fri, 10 Dec 2021 11:28:46 -0500 Subject: [PATCH] Revised day 1 --- src/day1/day1.rb | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/src/day1/day1.rb b/src/day1/day1.rb index 9976e2a..1ea409f 100644 --- a/src/day1/day1.rb +++ b/src/day1/day1.rb @@ -16,17 +16,33 @@ end puts "Amount of measurements larger than before: #{larger_than_before}" -larger_than_previous_window = 0 -previous_window = nil -window = [] -inputs.each_with_index do |input, index| - unless index+2 >= inputs.size # Handle the last window not overreaching - window = [inputs[index], inputs[index+1], inputs[index+2]] - if previous_window && window.reduce(:+) > previous_window.reduce(:+) - larger_than_previous_window += 1 - end - previous_window = window +# A struct to represent a three item sliding window +Window = Struct.new(:a, :b, :c) do + include Comparable + def <=>(other) + self.a + self.b + self.c <=> other.a + other.b + other.c end end +# Take a list of inputs and translate them into three section windows +def windowfy(inputs) + windowfied_inputs = [] + inputs.each_with_index do |_, index| + unless index + 2 >= inputs.size + window = Window.new(inputs[index], inputs[index+1], inputs[index+2]) + windowfied_inputs << window + end + end + return windowfied_inputs +end + +windowfied_inputs = windowfy(inputs) + +larger_than_previous_window = 0 +previous_window = nil +windowfied_inputs.each do |window| + larger_than_previous_window += 1 if previous_window && window > previous_window + previous_window = window +end + puts "Amount of measurements larger than preivous window: #{larger_than_previous_window}"