Advent of Code 2022 - Day 1: Calorie Counting

:: programming, puzzle, racket

Each day will have some preliminary setup code:

1
2
3
#lang iracket/lang #:require racket
(require "../advent.rkt")
(require threading)

Day 1 - Part 1

We’re given the following sample data:

1000
2000
3000

4000

5000
6000

7000
8000
9000

10000

This list represents the Calories of the food carried by five Elves:

  • The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories.
  • The second Elf is carrying one food item with 4000 Calories.
  • The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories.
  • The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories.
  • The fifth Elf is carrying one food item with 10000 Calories.

Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?

Here’s what we’ll do:

  • parse the input into a list of each elf’s list of calories
  • map the list-sum function over the list to collapse each elf’s list of calories to a total number
  • use the list-max function to obtain the maximum calories
1
(define in (parse-aoc 1 numbers #:sep "\n\n"))
----------------------------------------------------------------------------------------------------
day01.txt -> 10477 chars, 2254 lines; first 3 lines; last 2 lines:
----------------------------------------------------------------------------------------------------
10130
9819
4257
...
4980
6660
----------------------------------------------------------------------------------------------------
(parse 1) -> 250 entries:
----------------------------------------------------------------------------------------------------
((10130 9819 4257 8400 10994 3758 8326)
(9002 15602 1193 6805 10797)
...
(1654 6928 3317 4238 4796 4168 6225 1669 1109 4265 4980 6660))
----------------------------------------------------------------------------------------------------
1
2
(~> (map list-sum in)
    list-max)

69693

Part 2

For part 2 we need to find the top 3 elves carrying the most calories, so we’ll do the following:

  • map the list-sum function over the list to collapse each elf’s list of calories to a total number
  • sort the list in descending order
  • take the first 3 elements
  • sum these 3 elements
1
2
3
4
(~> (map list-sum in)
    (sort _ >)
    (take _ 3)
    (list-sum _))

200945

Refactor

Now that we have knowledge of both parts, we can factor out the common code into a solve function that is parameterized by the number of elves to sum:

1
2
3
4
5
(define (solve n)
  (~> (map list-sum in)
      (sort _ >)
      (take _ n)
      (list-sum _)))
1
(solve 1)

69693

1
(solve 3)

200945