Advent of Code 2022, Day 1: Calorie Counting

#ruby #advent of code 2022

Part A

Here is link to the puzzle. The first one is trivial. We have input file like this

1000
2000
3000

4000

5000
6000

7000
8000
9000

10000

Groups of numbers are separated by empty lines and task is to calculate the sum for each group and then output the largest one.

data = File.readlines("1.txt", chomp: true).map(&:to_i)

results = data.reduce([0]) do |acc, item|
  if item == 0
    acc.push(0)
  else
    acc[-1] += item
    acc
  end
end

puts results.max

I am reading all lines into an array and converting them to integers, empty lines will become zeros. Then I am reducing the input array. Accumulator in this case will be the array of final groups. I am starting with first group of sum 0. While enumerating each number I adding it to the last group. If there is a zero, it means there was an empty line and I need to create a new group. So another zero is added to the accumulator.

At last we select the maximum value.

Part B

Now I need to return the sum of top 3 groups. The code is almost the same. At the end I am sorting the final array, selecting last 3 items and summing them up.

data = File.readlines("1.txt", chomp: true).map(&:to_i)

results = data.inject([0]) do |acc, item|
  if item == 0
    acc.push(0)
  else
    acc[-1] += item
    acc
  end
end

puts results.sort[-3..-1].sum

Btw, there is a nice option for File.readlines method chomp: true that removes newline characters, so you don’t have to clean it up yourself.