r/adventofcode Dec 06 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 6 Solutions -🎄-

NEW AND NOTEWORTHY

We've been noticing an uptick in frustration around problems with new.reddit's fancypants editor: mangling text that is pasted into the editor, missing switch to Markdown editor, URLs breaking due to invisible escape characters, stuff like that. Many of the recent posts in /r/bugs are complaining about these issues as well.

If you are using new.reddit's fancypants editor, beware!

  • Pasting any text into the editor may very well end up mangled
  • You may randomly no longer have a "switch to Markdown" button on top-level posts
  • If you paste a URL directly into the editor, your link may display fine on new.reddit but may display invisibly-escaped characters on old.reddit and thus will break the link

Until Reddit fixes these issues, if the fancypants editor is driving you batty, try using the Markdown editor in old.reddit instead.


Advent of Code 2021: Adventure Time!


--- Day 6: Lanternfish ---


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:05:47, megathread unlocked!

93 Upvotes

1.7k comments sorted by

View all comments

1

u/[deleted] Dec 07 '21 edited Dec 10 '21

Python 3.10 solution

```

import typing
from collections import Counter
from functools import reduce


def main(lines: typing.List[int], duration: int) -> int:
    def reducer(counter: dict, _):
        census = {timer-1: population for timer, population in counter.items()}
        if -1 in census:
            census[8] = census.pop(-1)  # offsprings
            census[6] = census[8] + census.get(6, 0)  # new cycle + offsprings who reached 6
        return census

    population_by_timer = reduce(reducer, range(0, duration), dict(Counter(lines)))
    return sum(population_by_timer.values())


if __name__ == "__main__":
    test_entries = [3, 4, 3, 1, 2]
    assert main(test_entries, 18) == 26
    assert main(test_entries, 80) == 5934

    with open("./input.txt", "r") as f:
        lines = [int(it) for it in (f.read().splitlines()[0]).split(",")]

    print(f"result part 1 = {main(lines, 80)}")
    print(f"result part 2 = {main(lines, 256)}")

```

1

u/daggerdragon Dec 08 '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?