DEV Community

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

Posted on • Edited 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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay