DEV Community

benboorstein
benboorstein

Posted on

Advent of Code 2022 Day 1 Part 1 - Solution Only

// EXAMPLE input converted to a multiline string
const input =
`1000
2000
3000

4000

5000
6000

7000
8000
9000

10000`

// make an array of sub-arrays where each sub-array is one elf's calories, i.e., one grouping of nums
const groupedByElf =
    input // `1000\n2000\n3000\n\n4000\n\n5000\n6000\n\n7000\n8000\n9000\n\n10000`
        .split('\n\n') // ['1000\n2000\n3000', '4000', '5000\n6000', '7000\n8000\n9000', '10000']
        .map(str => str.split('\n').map(str => +str)) // [ [1000, 2000, 3000], [4000], [5000, 6000], [7000, 8000, 9000], [10000] ]

// find the total for each grouping and put these totals in one array
const eachGroupSum = groupedByElf.map(subArr => subArr.reduce((acc, curVal) => acc + curVal))

// pass this array (spread) into Math.max()
const highestCalGroup = Math.max(...eachGroupSum)

// log it
console.log(highestCalGroup) // 24000
Enter fullscreen mode Exit fullscreen mode

Top comments (0)