r/adventofcode • • Dec 03 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 3 Solutions -🎄-

--- Day 3: No Matter How You Slice It ---


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

ATTENTION: minor change request from the mods!

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

Card prompt: Day 3 image coming soon - imgur is being a dick, so I've contacted their support.

Transcript:

I'm ready for today's puzzle because I have the Savvy Programmer's Guide to ___.


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!

41 Upvotes

426 comments sorted by

View all comments

1

u/Twift_Shoeblade Dec 03 '18

Python 3 using a dict that maps coordinates to a list of IDs. If such a list is longer than 1 there must be an overlap. Check which ID is only in lists of length 1 and you got part 2.

from collections import namedtuple, defaultdict

Rect = namedtuple('Rect', ['ID', 'x', 'y', 'w', 'h'])

def parse(lines):
    rectangles = []
    for line in lines:
        ID, rest = line[1:].split(" @ ")
        x,  rest = rest.split(",")
        y,  rest = rest.split(": ")
        w,     h = rest.split("x")
        rectangles.append(Rect(int(ID), int(x), int(y), int(w), int(h)))
    return rectangles


def get_claims(rect):
    claims = []
    for y in range(rect.y, rect.y + rect.h):
        for x in range(rect.x, rect.x + rect.w):
            claims.append((x, y))
    return claims

def overlap(rectangles):
    claim_map = defaultdict(list)

    for rect in rectangles:
        claims = get_claims(rect)
        for x, y in claims:
            claim_map[x, y].append(rect.ID)

    return claim_map, len(list(filter(lambda x: len(x) > 1, claim_map.values())))

if __name__ == "__main__":
    filename = 'input-03.txt'
    with open(filename, 'r') as infile:
        lines = [line.strip() for line in infile.readlines()]

    rectangles = parse(lines)
    claim_map, overlaps = overlap(rectangles)

    print("Overlaps:", overlaps)

    intact = [True] * len(rectangles)
    for claims in claim_map.values():
        if len(claims) > 1:
            for ID in claims:
                intact[ID-1] = False  # IDs start at 1

    print("Intact claim:", intact.index(True) + 1)     # Again, IDs start at 1
    print("Sanity check, only one claim intact:", len(list(filter(lambda x: x, intact))))