#!/usr/bin/env python3
#Advent of Code
#2021 Day 6, Part 1
#Solution by James C. (https://github.com/JamesMCo)
importos,syssys.path.append(os.path.abspath("../.."))importunittest,util.readfromutil.testsimportrundefsolve(puzzle_input):classLanternfish:def__init__(self,timer):self.timer=timerdeftick(self,new_fish_list):ifself.timer==0:self.timer=6new_fish_list.append(Lanternfish(8))else:self.timer-=1fish=[Lanternfish(f)forfinpuzzle_input]fordayinrange(1,81):new_fish=[]forfinfish:f.tick(new_fish)fish+=new_fishreturnlen(fish)defmain():puzzle_input=util.read.as_int_list(",")fish=solve(puzzle_input)print("The number of lanternfish after 80 days is "+str(fish)+".")classAOC_Tests(unittest.TestCase):deftest_ex1(self):returnself.assertEqual(solve([3,4,3,1,2]),5934)if__name__=="__main__":run(main)
#!/usr/bin/env python3
#Advent of Code
#2021 Day 6, Part 2
#Solution by James C. (https://github.com/JamesMCo)
importos,syssys.path.append(os.path.abspath("../.."))importunittest,util.readfromutil.testsimportrundefsolve(puzzle_input):classLanternfish:def__init__(self,timer,count):self.timer=timerself.count=countdeftick(self):ifself.timer==0:self.timer=6returnTrueelse:self.timer-=1returnFalsefish=[]defget_fish_by_timer(t):candidate=[fforfinfishiff.timer==t]ifcandidate:returncandidate[0]else:new_fish=Lanternfish(t,0)fish.append(new_fish)returnnew_fishfortinpuzzle_input:get_fish_by_timer(t).count+=1fordayinrange(1,257):# Tick timers of all fish
new_fish_count=0forfinfish:iff.tick():new_fish_count+=f.count# When a timer ticks at 0, it resets to 6, but there might be another fish that ticked from 7 to 6
# As a result, there might be multiple fish objects with a timer of 6 (which is bad, and defeats the
# entire goal of having a single object for each timer!)
# Therefore, we need to merge these objects in to one object, done here by getting the counts of both
# existing objects, creating a new object with the sum of these, removing the existing objects from
# the list, and adding the new one to the list.
iflen(duplicates:=[(i,f)fori,finenumerate(fish)iff.timer==6])>1:replacement=Lanternfish(6,sum(f[1].countforfinduplicates))forfinduplicates[::-1]:fish.pop(f[0])fish.append(replacement)ifnew_fish_count:get_fish_by_timer(8).count+=new_fish_countreturnsum(f.countforfinfish)defmain():puzzle_input=util.read.as_int_list(",")fish=solve(puzzle_input)print("The number of lanternfish after 256 days is "+str(fish)+".")classAOC_Tests(unittest.TestCase):deftest_ex1(self):returnself.assertEqual(solve([3,4,3,1,2]),26984457539)if__name__=="__main__":run(main)