From 28db35af73c4bfc63f0c3bc5b5c56d4430987e16 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Sun, 1 Dec 2024 21:10:38 -0800 Subject: [PATCH] [2024][ruby][2.x] --- 2024/ruby/day_02.rb | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 2024/ruby/day_02.rb diff --git a/2024/ruby/day_02.rb b/2024/ruby/day_02.rb new file mode 100644 index 0000000..f306a70 --- /dev/null +++ b/2024/ruby/day_02.rb @@ -0,0 +1,30 @@ +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 + +def dampened(report) + return enum_for(__method__, report) unless block_given? + + (0...report.length).each do |i| + yield report[0...i] + report[i+1..] + end +end + +pp input.count {|report| + # part one + # safe(report) + + # part two + safe(report) || dampened(report).any? { safe(_1) } +} + +__END__ +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9