r/adventofcode • • Dec 06 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 6 Solutions -🎄-

--- Day 6: Chronal Coordinates ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 6

Transcript:

Rules for raising a programmer: never feed it after midnight, never get it wet, and never give it ___.


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

edit: Leaderboard capped, thread unlocked at 0:26:52!

32 Upvotes

387 comments sorted by

View all comments

1

u/TheVarmari Dec 07 '18

JavaScript in dev console (#10671, #10042)
Again, a day late, but I'm pretty satisfied with the code. Could probably be a bit neater and more optimized, but it gets the result quickly enough.

const input = $('pre').textContent.trim().split('\n');
const coordinates = input.map(v => v.split(', ').map(v => Number(v)));

const prefix = 'color: blue';
const text = 'color: navy';
const highlight = 'color: red';

const xs = coordinates.map(v => v[0]);
const ys = coordinates.map(v => v[1]);

const xmin = Math.min(...xs);
const xmax = Math.max(...xs);
const ymin = Math.min(...ys);
const ymax = Math.max(...ys);

const infinites = [[]];
var safes = [];
var area = {};

for (let x = xmin - 2; x < xmax + 2; x++) {
    for (let y = ymin - 2; y < ymax + 2; y++) {
        let outside = (x < xmin || x > xmax || y < ymin || y > ymax);
        let coordinateDist = coordinates.map(v => { return [v, Math.abs(x - v[1]) + Math.abs(y - v[0])]; });
        let dists = coordinateDist.map(v => v[1]);
        let totalDist = dists.reduce((a, b) => { return a+b; });
        let min = Math.min(...dists);

        if (totalDist < 10000 && !outside) safes.push([x, y]);
        if (dists.filter(v => v===min).length === 1) {
            let closest = coordinateDist[dists.findIndex(v => v===min)][0];
            if (infinites.includes(closest)) continue;
            if (outside) {
                infinites.push(closest);
                if (area[`${closest[0]}.${closest[1]}`]) delete area[`${closest[0]}.${closest[1]}`];
                continue;
            }
            area[`${closest[0]}.${closest[1]}`] = (area[`${closest[0]}.${closest[1]}`] || 0) + 1;
        }
    }
}

console.log(`%c(Part 1) %cThe largest non-infinite area is %c${Math.max(...Object.values(area))} %cunits.`, prefix, text, highlight, text);
console.log(`%c(Part 2) %cThere are %c${safes.length} %csafe spots.`, prefix, text, highlight, text);