Advent of Code 2022 - Day 1: Calorie Counting Solution
Straight-forward data manipulationPart 1
Calculate the total calories carried by each Elf
Implementation
1const fs = require("fs")23const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/)45const SEPARATOR = ""67const aggregatedData = data.reduce(8 (acc, el) => {9 if (el === SEPARATOR) {10 acc.totalCarries.push(acc.sum)11 acc.sum = 012 } else {13 acc.sum += Number(el)14 }1516 return acc17 },18 { totalCarries: [], sum: 0 }19)2021const res = Math.max(...aggregatedData.totalCarries)2223console.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")23const data = fs.readFileSync("./input", "utf-8").split(/\r?\n/)45const SEPARATOR = ""67const aggregatedData = data.reduce(8 (acc, el) => {9 if (el === SEPARATOR) {10 acc.totalCarries.push(acc.sum)11 acc.sum = 012 } else {13 acc.sum += Number(el)14 }1516 return acc17 },18 { totalCarries: [], sum: 0 }19)2021const res = aggregatedData.totalCarries22 .sort((a, b) => b - a)23 .slice(0, 3)24 .reduce((acc, el) => acc + el, 0)2526console.log(res)
References
Comments
Loading comments...
Tags
adventofcode
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
Advent of Code 2022 - Day 3: Rucksack Reorganization
Find shared item and calculate
Previous Post
LeetCode: Nearest Exit from Entrance in Maze
BFS with a notice