Advent of Code 2022 - Day 1: Calorie Counting Solution

Straight-forward data manipulation

Part 1

Calculate the total calories carried by each Elf

Implementation

1const fs = require("fs")
2
3const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/)
4
5const SEPARATOR = ""
6
7const aggregatedData = data.reduce(
8 (acc, el) => {
9 if (el === SEPARATOR) {
10 acc.totalCarries.push(acc.sum)
11 acc.sum = 0
12 } else {
13 acc.sum += Number(el)
14 }
15
16 return acc
17 },
18 { totalCarries: [], sum: 0 }
19)
20
21const res = Math.max(...aggregatedData.totalCarries)
22
23console.log(res)

Part 2

Same as Part 1, with additional steps

  • take aggregatedData.totalCarries
  • sort descending
  • take the first 3 value
  • calculate sum

Implementation

1const fs = require("fs")
2
3const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/)
4
5const SEPARATOR = ""
6
7const aggregatedData = data.reduce(
8 (acc, el) => {
9 if (el === SEPARATOR) {
10 acc.totalCarries.push(acc.sum)
11 acc.sum = 0
12 } else {
13 acc.sum += Number(el)
14 }
15
16 return acc
17 },
18 { totalCarries: [], sum: 0 }
19)
20
21const res = aggregatedData.totalCarries
22 .sort((a, b) => b - a)
23 .slice(0, 3)
24 .reduce((acc, el) => acc + el, 0)
25
26console.log(res)

References

Original problem

Comments

Loading comments...

Tags

adventofcode

Next Post

Advent of Code 2022 - Day 3: Rucksack Reorganization

Find shared item and calculate

Previous Post

HoningJS

Search Posts