Created
April 22, 2026 04:37
-
-
Save donilan/a27844c8f1ee0bd8938f4757a0096f75 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # frozen_string_literal: true | |
| def safe?(levels) | |
| # Adjacent differences | |
| diffs = levels.each_cons(2).map { |a, b| b - a } | |
| # Rule 1: All increasing or all decreasing | |
| all_increasing = diffs.all? { |d| d > 0 } | |
| all_decreasing = diffs.all? { |d| d < 0 } | |
| return false unless all_increasing || all_decreasing | |
| # Rule 2: Differences are between 1 and 3 (inclusive) | |
| diffs.all? { |d| d.abs >= 1 && d.abs <= 3 } | |
| end | |
| input_file = File.join(__dir__, 'input.txt') | |
| unless File.exist?(input_file) | |
| puts "Input file not found: #{input_file}" | |
| exit 1 | |
| end | |
| safe_reports_count = 0 | |
| File.foreach(input_file) do |line| | |
| next if line.strip.empty? | |
| levels = line.split.map(&:to_i) | |
| if safe?(levels) | |
| safe_reports_count += 1 | |
| end | |
| end | |
| puts "Number of safe reports: #{safe_reports_count}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment