DEV Community

Cover image for Advent of Code 2022 with Ruby day 01
Ankit Pariyar
Ankit Pariyar

Posted on • Updated on

Advent of Code 2022 with Ruby day 01

Problem

  • We have text file which look like this
4514
8009

6703
1811
4881

3905
Enter fullscreen mode Exit fullscreen mode
  • Above number represents Calories of the food carried by 3 Elves. Blank line separate the food carried by each Elves

  • We have to find total Calories of the food carried by Elf carrying the most Calories

Solution

First let's break down problem

  • Reading text file
  • Find out total calories carried by each Elves
  • Find out maximum out of that calories
calories_carried_by_each_elves = 0
max_calories = 0

File.foreach('day_01.txt') do |calories|
  if calories.to_i.positive?
    calories_carried_by_each_elves += calories.to_i
  else
    max_calories = calories_carried_by_each_elves if calories_carried_by_each_elves > max_calories
    calories_carried_by_each_elves = 0
  end
end

puts max_calories

Enter fullscreen mode Exit fullscreen mode

Top comments (0)