Skip to content

Commit

Permalink
Add 2024, day 2
Browse files Browse the repository at this point in the history
  • Loading branch information
bewuethr committed Dec 2, 2024
1 parent 8b0943f commit f11d754
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
21 changes: 21 additions & 0 deletions 2024/day02/day02a
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env ruby

def increasing(levels) = levels.eql?(levels.sort)

def decreasing(levels) = levels.eql?(levels.sort.reverse)

def max_diff(levels)
levels.each_cons(2).to_a.all? do |a, b|
diff = (a - b).abs
(1..3).cover?(diff)
end
end

file = File.open(ARGV[0])

safe = file.readlines(chomp: true).count do |report|
levels = report.split.map(&:to_i)
(increasing(levels) || decreasing(levels)) && max_diff(levels)
end

puts safe
29 changes: 29 additions & 0 deletions 2024/day02/day02b
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#!/usr/bin/env ruby

def increasing(levels) = levels.eql?(levels.sort)

def decreasing(levels) = levels.eql?(levels.sort.reverse)

def max_diff(levels)
levels.each_cons(2).to_a.all? do |a, b|
diff = (a - b).abs
(1..3).cover?(diff)
end
end

def are_safe(levels) = (increasing(levels) || decreasing(levels)) && max_diff(levels)

def is_safe(report)
levels = report.split.map(&:to_i)
return true if are_safe(levels)

levels.each_with_index.any? do |level, idx|
copy = levels.dup
copy.delete_at(idx)
are_safe(copy)
end
end

file = File.open(ARGV[0])

puts file.readlines(chomp: true).count { is_safe(_1) }

0 comments on commit f11d754

Please sign in to comment.