Lantern Fish - Advent of Code 2021 Day 6

 


Today's problem involves finding the total number of Lanternfish on a given day

A full description of the problem can be found here - https://adventofcode.com/2021/day/6

Understanding the problem

The given input file contains a list of lanternfish, each value represents an internal timer at Day 0


The timer counts down to zero every day and then resets to 6. Upon reset a new lanternfish is spawned. New lanternfishes are spawned with an internal timer of 8.

The goal is to figure out how many lanternfishes are present on Days 80 and 256

Solving it

We can represent each lanternfish as an object or a tuple. We need both the internal timer and the current day


For each of these initial set of lanternfishes we can determine ALL the descendant lanternfishes. 

This can be a function that 

  • Determines the initial set of children 
  • Recursively iterates over the children and subsequent children until the current day exceeds the day specified in the problem (80 or 256)
  • Return a count of the children

Code

with open('input.txt') as f:
    lines = f.readlines()

# read all lanternFish from feed
# lanterfish is a tuple of internalTimer and currentDay (initialized to zero)
lanternFish = [ (int(i),0) for i in lines[0].split(',') ] 

memo = {}
maxDays = 256 # 80  # part 2 and 1

def determineOffSpringCount(lanternFish):

    # use a dict to optimize
    c = memo.get(lanternFish)
    if c != None:
       return c

    (internalTimer,day) = lanternFish

    firstOffspringDay = day + internalTimer + 1 # this will be the start of our range

    if firstOffspringDay > maxDays:
        return 0

    # get all the offsprings for this lantern fish
    offSprings = [ (8,i) for i in range(firstOffspringDay,maxDays+1,7) ]

    count = len(offSprings)

    # print(lanternFish)
    # print(offSprings)

    # recursively determine the offsprings of the offsprings
    for i in offSprings:
        count += determineOffSpringCount(i)

    memo[lanternFish] = count

    return count


count = 0

for i in lanternFish:
    count += 1 + determineOffSpringCount(i) 

print(count)