Sean McLemon | Advent of Code

Home | Czech | Blog | GitHub | Advent Of Code | Notes


2015-12-13 - Knights of the Dinner Table

(original .ipynb)

Puzzle input is a set of instructions describing how happy some people would be to sit next to someone else at a dinner table. Part one involves finding the arrangement with the maximum happiness-level. Part two involves adding "me" into the mix, where I'm ambivalent about everyone (happiness change of 0) and they're ambivalent about me.

from collections import defaultdict
from itertools import permutations

puzzle_input_str = open("./puzzle_input/day13.txt").read()


def parse_units(gain_lose, count):
    return int(count) if gain_lose == "gain" else -int(count)


def parse_line(line):
    tokens = line.split(" ")
    return (
        tokens[0],
        parse_units(tokens[2], tokens[3]),
        tokens[-1].strip(".")
    )

def parse_rules(input_str, include_me):
    raw_rules = list(parse_line(line) for line in input_str.split("\n"))
    rules = defaultdict(dict)
    for subj, change, obj in raw_rules:
        rules[subj][obj] = change
        
    if include_me:
        for person in list(rules.keys()):
            rules["Me"][person] = 0
            rules[person]["Me"] = 0
    
    return rules
    

def calc_happiness(seating, rules):
    total = 0
    for i, person in enumerate(seating):
        left_person = seating[i-1] if i > 0 else seating[-1]
        right_person = seating[i+1] if i+1 < len(seating) else seating[0]
        total += rules[person][left_person]
        total += rules[person][right_person]
    return total


def part_one(input_str, include_me=False):
    rules = parse_rules(input_str, include_me)
    
    max_happiness = 0
    for seating in permutations(list(rules.keys())):
        happiness = calc_happiness(seating, rules)
        if max_happiness < happiness:
            max_happiness = happiness
    
    return max_happiness


test_input_str = """Alice would gain 54 happiness units by sitting next to Bob.
Alice would lose 79 happiness units by sitting next to Carol.
Alice would lose 2 happiness units by sitting next to David.
Bob would gain 83 happiness units by sitting next to Alice.
Bob would lose 7 happiness units by sitting next to Carol.
Bob would lose 63 happiness units by sitting next to David.
Carol would lose 62 happiness units by sitting next to Alice.
Carol would gain 60 happiness units by sitting next to Bob.
Carol would gain 55 happiness units by sitting next to David.
David would gain 46 happiness units by sitting next to Alice.
David would lose 7 happiness units by sitting next to Bob.
David would gain 41 happiness units by sitting next to Carol."""


assert 330 == part_one(test_input_str)

print("part one:", part_one(puzzle_input_str))
part one: 709
def part_two(input_str):
    return part_one(input_str, True)

print("part two:", part_two(puzzle_input_str))
part two: 668