Advent of Code Day 1

sethcalebweeks

Caleb Weeks

Posted on December 1, 2022

Advent of Code Day 1

Links

Highlights

  • The first trick I used here was splitting the original input by two lines (\n\n) to group all the values for each elf together. Then I split each of these substrings on a single line break to get the individual calorie counts.
  • The second trick uses reduce to add the calorie counts together. Since the accumulator is an integer and the values are strings, we need to convert the values to integers as we go and provide an initial value of 0. For some reason, the accumulator is the second argument to the function, which I didn't know until today.
defmodule Day01 do
  use AOC

  def part1 do
    input(1)
    ~> String.split("\n\n")
    ~> Enum.map(fn elf ->
      elf
      ~> String.split("\n")
      ~> Enum.reduce(0, fn a, b -> String.to_integer(a) + b end)
    end)
    ~> Enum.max()
  end

  def part2 do
    input(1)
    ~> String.split("\n\n")
    ~> Enum.map(fn elf ->
      elf
      ~> String.split("\n")
      ~> Enum.reduce(0, fn a, b -> String.to_integer(a) + b end)
    end)
    ~> Enum.sort(:desc)
    ~> Enum.slice(0, 3)
    ~> Enum.reduce(0, fn a, b -> a + b end)
  end

end
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
sethcalebweeks
Caleb Weeks

Posted on December 1, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Advent of Code Day 11
adventofcode Advent of Code Day 11

December 12, 2022

Advent of Code Day 10
adventofcode Advent of Code Day 10

December 11, 2022

Advent of Code Day 9
adventofcode Advent of Code Day 9

December 10, 2022

Advent of Code Day 8
adventofcode Advent of Code Day 8

December 8, 2022

Advent of Code Day 7
adventofcode Advent of Code Day 7

December 7, 2022