Snippet

advent_of_code/2024_2.rb
Code:
# Advent of Code 2024, Day 2: Red-Nosed Reports

# https://adventofcode.com/2024/day/2

require_relative './helpers.rb'

def is_inc_or_dec?(r)
  r.sort == r || r.sort.reverse == r
end

def is_gradual?(r)
  Array.new(r.size - 1) { |i| [r[i], r[i + 1]] }
    .map { |a, b| (a - b).abs }
    .as { |g| g.min > 0 && g.max < 4 }
end

def is_safe?(r)
  is_inc_or_dec?(r) && is_gradual?(r)
end

def part_one(data)
  data.count { |d| is_safe?(d) }
end

def part_two(data)
  data.count { |d| d.combination(d.size - 1).any? { |c| is_safe?(c) } }
end

def solve(data)
  data.map! { |line| line.split(' ').map(&:to_i) }
  [part_one(data), part_two(data)]
end

puts solve(get_dataset(year: 2024, day: 2, type: 'example'))
puts solve(get_dataset(year: 2024, day: 2, type: 'input'))
Output:
2
4
421
476