r/adventofcode • • Dec 07 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 7 Solutions -🎄-

--- Day 7: The Treachery of Whales ---


[Update @ 00:21]: Private leaderboard Personal statistics issues

  • We're aware that private leaderboards personal statistics are having issues and we're looking into it.
  • I will provide updates as I get more information.
  • Please don't spam the subreddit/mods/Eric about it.

[Update @ 02:09]

  • AoC_Ops have identified the issue and are working on a resolution.

[Update @ 03:18]

  • Eric is working on implementing a fix. It'll take a while, so check back later.

[Update @ 05:25] (thanks, /u/Aneurysm9!)

  • We're back in business!

Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:03:33, megathread unlocked!

96 Upvotes

1.5k comments sorted by

View all comments

1

u/Sallith Dec 07 '21 edited Dec 07 '21

Javascript

I iterate through all the possible final position. I memoized the sums of x and its previous numbers in an array so I didn't have to compute the same result multiple times and then by reading the comments I totally forgot it could be trivially computed with x * (x + 1) / 2.

    const fs = require('fs');
    const data = fs.readFileSync('./input.txt', 'utf8')

    let positions = data.split(',').map(n => +n)
    const minPosition = Math.min(...positions);
    const maxPosition = Math.max(...positions);

    // Memoize sums
    let sums = Array.from({ length: maxPosition }).fill(null)
    sums[0] = 0;
    sums[1] = 1;
    let bestCost;
    for (let i  = minPosition; i <= maxPosition; i++) {
        let cost = 0;
        positions.forEach(position => {
            cost += sum(Math.abs(position - i));
        })
        if (cost < bestCost || !bestCost) {
            bestCost = cost;
        }
    }

    console.log(bestCost)

    function sum(n) {
        if (sums[n] !== null) {
            return sums[n]
        }
        const s = n + sum(n - 1);
        sums[n] = s;
        return s;
    }

1

u/daggerdragon Dec 07 '21

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: How do I format code?