Advent of Code 2022, Day 4: Camp Cleanup

#ruby #advent of code 2022

Part A

Day 4 is about overlapping ranges. The elves need to clean up the camp and they have assigned ranges of sections they need to clean. But some ranges do overlap and elves want to avoid duplicating the work.

We need to help them. Our input looks like this:

2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8

Each line represent ranges for pair of elves. In the Part A we need to know in how many pairs one range fully covers another. For example, 2-8 fully covers 3-7.

Here is the code:

data = File.readlines("4.txt").map(&:strip)

data.map! do |line|
  ranges = line.split(",").map do |range|
    a, b = range.split("-").map(&:to_i)
    a..b
  end

  ranges[0].cover?(ranges[1]) || ranges[1].cover?(ranges[0])
end

puts data.select { |item| item }.size

I am parsing input data into an array of two ranges and then checking if first range covers the second one or vice versa. The result is an array of boolean values, so in the end we need to count how many trues there are.

Part B

In this part instead of checking for full coverage, we need to check if ranges overlap. The check is similar, we can just check if one range covers the start of another range.

data = File.readlines("4.txt").map(&:strip)

data.map! do |line|
  ranges = line.split(",").map do |range|
    a, b = range.split("-").map(&:to_i)
    a..b
  end

  ranges[0].cover?(ranges[1].first) || ranges[1].cover?(ranges[0].first)
end

puts data.select { |item| item }.size