DEV Community

benboorstein
benboorstein

Posted on

Advent of Code 2022 Day 1 Part 2 - Solution Only

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

4000

5000
6000

7000
8000
9000

10000`

// use my work from Part 1 to get the array of sums
    // 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)) // [6000, 4000, 11000, 24000, 10000]

// sort array from smallest to largest
const eachGroupSumSorted = eachGroupSum.sort((a, b) => a - b) // [4000, 6000, 10000, 11000, 24000]

// push and pop, push and pop, push and pop (3 times)
let threeHighest = []
threeHighest.push(eachGroupSumSorted.pop())
threeHighest.push(eachGroupSumSorted.pop())
threeHighest.push(eachGroupSumSorted.pop())
// console.log(threeHighest) // [24000, 11000, 10000]

// sum those three values
const sumOfThreeHighest = threeHighest.reduce((acc, curVal) => acc + curVal)

// log it
console.log(sumOfThreeHighest) // 45000
Enter fullscreen mode Exit fullscreen mode

Top comments (0)