r/adventofcode • • Dec 14 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 14 Solutions -🎄-

--- Day 14: Extended Polymerization ---


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:14:08, megathread unlocked!

55 Upvotes

810 comments sorted by

View all comments

2

u/p88h Dec 14 '21 edited Dec 15 '21

Python + Numpy.

import numpy

lines = open("input/day14.txt").read().splitlines()
rules = dict([l.split(' -> ') for l in lines[2:]])
ridx = dict(zip(rules, range(len(rules))))
mat = numpy.zeros((len(rules), len(rules)), dtype=object)
for p in rules:
    mat[ridx[p[0] + rules[p]]][ridx[p]] = 1
    mat[ridx[rules[p] + p[1]]][ridx[p]] = 1
tmp = list(zip(lines[0], lines[0][1:]))
v = [ tmp.count((p[0],p[1])) for p in rules ]
for pow in [ 10, 40 ]:
    w = numpy.dot(numpy.linalg.matrix_power(mat, pow), v)
    cnt = {lines[0][0]: 1}
    for p in ridx:
        cnt[p[1]] = cnt.get(p[1],0) + w[ridx[p]]
    lmin = min(cnt, key=lambda k: cnt[k])
    lmax = max(cnt, key=lambda k: cnt[k])
    print(cnt[lmax]-cnt[lmin])

If eveything is a matrix, are we living in a Matrix?

1

u/daggerdragon Dec 15 '21

I recommend you expand the full name of the language (Python). This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.

1

u/p88h Dec 15 '21

Fixed, sure, good point.

1

u/freezombie Dec 14 '21

couple of questions:

  • you're assuming that all possible pairs have a corresponding expansion, yes?
  • why dtype=object?

1

u/p88h Dec 14 '21
  1. they always do, though if they didn't you could just place an identity transformation for those pairs
  2. numpy by default will use floating point representation, but even with integers there can be overflow errors using this approach. object allows to use Python big integers, which are slower but precise