view the Advent of Code 2021 Day 6 challenge
# Setup - load any packages
import numpy as np
from collections import Counter
def LoadData(filename):
return np.loadtxt(filename, dtype='int', delimiter=',')
def GenerateLanternFish(fish, days):
# fish = numpy array of the starting fish
# days = int of days to run the model for
for day in range(days):
#for each day in days
# decrease fish age by 1
fish=fish-1
# calculate how many new fish need to be created (age < 0)
new_fish_count=(fish < 0).sum()
# reset any fish that have just made new fish to 6
fish=np.where(fish <0 , 6, fish)
# add the new fish with a starting value of 8
if new_fish_count>0:
# create an array of new fish with age 8
new_fish=np.full(new_fish_count, 8)
fish=np.append(fish, new_fish)
# return the number of fish
return fish.size
day6_raw=LoadData('day6_data.txt')
p1_answer=GenerateLanternFish(day6_raw, 80)
print(f'answer = {p1_answer}')
answer = 387413
view the Advent of Code 2021 Day 6 challenge Part 2
Alternative approach for part 2 as part 1s brute force is too resource intensive for 256 days. (Should have done it this way first)
def GenerateLanternFish(fish, days):
# add the fish to a counter
count = Counter(fish)
for day in range(days):
# loop through each day
# store fish on zero as these become 6 and also generate new fish with count of 8
mothers = count[0]
# now move each count down 1 to age the fish
count[0] = count[1]
count[1] = count[2]
count[2] = count[3]
count[3] = count[4]
count[4] = count[5]
count[5] = count[6]
count[6] = count[7]
# Add on the fish that reset becuase they had fish
count[6] = count[6] + mothers
count[7] = count[8]
# Add the newly born fish
count[8] = mothers
# return the sum of all fish
return sum(count.values())
day6_raw=LoadData('day6_data.txt')
p2_answer=GenerateLanternFish(day6_raw, 256)
print(f'answer = {p2_answer}')
answer = 1738377086345