From c08e5d3752fa0354146746eba75e99b4062c649c Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Sun, 1 Dec 2024 21:18:57 -0800 Subject: [PATCH] [2024][ruby][2.x] refactored --- 2024/ruby/day_02.rb | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/2024/ruby/day_02.rb b/2024/ruby/day_02.rb index f306a70..58adfaa 100644 --- a/2024/ruby/day_02.rb +++ b/2024/ruby/day_02.rb @@ -1,25 +1,27 @@ -input = DATA.readlines(chomp: true).map { _1.split(/\s+/).map(&:to_i) } - -def safe(report) - deltas = report.each_cons(2).map { _1 - _2 } - (deltas.all?(&:negative?) || deltas.all?(&:positive?)) && (deltas.all? { (1..3).cover?(_1.abs) }) -end +Report = Data.define(:levels) do + def safe? + deltas = levels.each_cons(2).map { _1 - _2 } + (deltas.all?(&:negative?) || deltas.all?(&:positive?)) && (deltas.all? { (1..3).cover?(_1.abs) }) + end -def dampened(report) - return enum_for(__method__, report) unless block_given? + def dampened + return enum_for(__method__) unless block_given? - (0...report.length).each do |i| - yield report[0...i] + report[i+1..] + (0...levels.length).each do |i| + yield Report.new(levels[0...i] + levels[i+1..]) + end end end -pp input.count {|report| - # part one - # safe(report) +input = DATA.readlines(chomp: true) + .map { _1.scan(/\d+/).map(&:to_i) } + .map { Report.new(_1) } + +# part one +pp input.count(&:safe?) - # part two - safe(report) || dampened(report).any? { safe(_1) } -} +# part two +pp input.count { _1.safe? || _1.dampened.any?(&:safe?) } __END__ 7 6 4 2 1