This one seemed like it might be hard, but then I realized that part1 was fast enough that I could just do the first couple hundred and watch for loops.
I didn't get a loop, but I did see a consistency! I made a quick function to seek for that and voila! (That's French, for 'voila!')
Haha, love your visualisations! Always fascinating how such simple things can create such complexity.
(Slightly off-topic, but I once came across these "meta-pixel" in Conway's Game of Life which literally gave me goose bumps: youtube.com/watch?v=xP5-iIeKXE8)
Ryan is an engineer in the Sacramento Area with a focus in Python, Ruby, and Rust. Bash/Python Exercism mentor. Coding, physics, calculus, music, woodworking. Looking for work!
Ryan is an engineer in the Sacramento Area with a focus in Python, Ruby, and Rust. Bash/Python Exercism mentor. Coding, physics, calculus, music, woodworking. Looking for work!
Full marks + animations + bonus plant puns! Checking for loops was a good idea. I didn't think of that until I cheated and looked at the discussion here :/
Part 1 would be easy for anyone who has ever coded Game of Life (I somehow managed to leave out last line on the input so I spent unreasonable amount of time debugging).
For part 2 after seeing that even 10k generations take a lot I started to look for a pattern and came up with a formula to calculate value for any generation bigger than ~160 (that's when it starts to loop).
<?php$file=fopen("input.txt","r")orexit("Unable to open file");// $file = fopen("input_test.txt", "r") or exit("Unable to open file");while(!feof($file)){$array[]=fgets($file);}fclose($file);returnarray_filter($array);?>
Part 1 was easy. I used regular expressions to match the rules against the pots, and I needed to keep a record at what position the current pattern starts.
#!/usr/bin/perlusewarnings;usestrict;usefeatureqw{ say };my$state=<>;$state=~s/[^#.]//g;<>;my%rule;while(<>){chomp;my($left,$right)=split/\s*=>\s*/;$rule{$left}=$right;}my$start_at=0;for(1..20){substr$state,0,0,'...';--$start_at;$state.='...';my$new;while($state=~/(?=(.....))/g){my$before=$1;if(exists$rule{$before}&&'#'eq$rule{$before}){$new.='#';}else{$new.='.';}}$state=$new;$state=~s/\.+$//;$state=~s/^(\.*)//;$start_at+=length$1;}my$count=0;$count+=$start_at-1+pos$statewhile$state=~/#/g;say$count;
Running it for many more than 20 steps I discovered the pattern stays the same, only moving to the right. So I printed its value for two different numbers, the rest was just two equations:
20000a + b = 2041377 20002a + b = 2041581 b = 2041377 - 20000a 20002a + 2041377 - 20000a = 2041581 2a + 2041377 = 2041581 2a = 204 a = 102 b = 2041377 - 20000 * 102 b = 1377
Part 1 is easy enough - the tricky part is that the space is unbounded. I modelled the row of plants as a boolean array where the first and last are always true (i.e. the left and rightmost plants) and the position of the leftmost plant is stored separately. Thus if the row grows to the right the array gets longer and the origin stays the same, and if it grows to the left the array also gets longer but the origin decreases.
data classState(valplants:BooleanArray,valorigin:Long)
At first I translated the rules into a map of BooleanArray to Boolean but the lookups seemed to have trouble so I converted the five bits of a rule's left hand side to an integer and used that as the key:
data classRegion(valvalue:Int){constructor(states:List<Boolean>):this(states.fold(0){v,b->(vshl1)or(if(b)1else0)})overridefuntoString():String=listOf(16,8,4,2,1).map{b->if(valueandb!=0)'#'else'.'}.joinToString("")}
The use of && and || for logic and and and or for boolean operations in Kotlin seems the wrong way round. Yes you want to bring C / Java programmers with you when you introduce a new language, but in this case I'd have gone for Python's readability.
Parsing
Parsing the input data of course uses JParsec. It's just so much easier not to have to deal with questions like "did I find all the parts?" or "does the rule have exactly 5 positions on the left" etc. It either parses or it throws an error and tells you the line and column where the parsing failed.
At first you read part 2 and think "oh, just up the iteration count to 50 billion".
No.
The secret is that the rules inevitably lead to a repeating pattern. Work out where the loop is, work out how many loops occur in 50 billion iterations, then you only need to run the loop once. The tricky part in this puzzle is that the same pattern of plants may occur with a different origin. Conway's original Game of Life is famous for its walker structures that move across the 2D space, replicating themselves perfectly.
I built a map keyed by a string representation of the plant pattern. When the current state already exists in the map, we have detected a loop. The value stored in the map describes the start of the loop. Then it's just a matter of determining the number of loops, the length of the last incomplete loop (if present), assemble the state at the end of the final loop and finish the sequence. All while avoiding 50 billion opportunities for an off-by-one error.
In my case the loop was only one iteration long, but I suspect that's not true for everyone. My lastState calculation's else branch is therefore never taken so I don't have full confidence that's the correct logic.
I should also point out I took eight attempts to submit the right answer, constantly tweaking my code before realising I was doing 5 billion iterations, not 50 billion. I should have used the underscore syntax for the big number earlier.
const{readFile}=require('./reader');const{parseInput,processGenerations,sumPots}=require('./12-common');(async()=>{constlines=awaitreadFile('12-input.txt');const{initialState,notes}=parseInput(lines);constlastGeneration=processGenerations(initialState,notes,20,false);constpotsSum=sumPots(lastGeneration);console.log(`The sum of the numbers of all pots is ${potsSum}`);})();
12b.js
const{readFile}=require('./reader');const{parseInput,processGeneration,processGenerations,sumPots}=require('./12-common');(async()=>{constlines=awaitreadFile('12-input.txt');const{initialState,notes}=parseInput(lines);constinitialBatch=processGenerations(initialState,notes,160,false);constinitialSum=sumPots(initialBatch);console.log(`The sum for the first 160 batch is ${initialSum}`);constdiffBatch=processGeneration(initialBatch,notes);constdiffSum=sumPots(diffBatch)-initialSum;console.log(`The sum for the just 1 generation is ${diffSum}`);consttotalSum=initialSum+diffSum*(50000000000-160);console.log(`The total sum is ${totalSum}`);})();
Here is currently my Python code for today. Took me some time because I did not understand that we had to sum the indeces of the pots(!).
For part 2 I am looking for loops in the evolution, so that if we reach a plant state (regardless of the indeces) that we have reached before, we loop over those same circular steps without recalculation until reaching to the end.
I could clean up a little, especially the code that cleans up the borders. Maybe if I find time I will do it, but I first hope to later make a Golang solution based on my Python code.
importrewithopen('input')asf:data=f.readlines()# Read plants and add padding of statically empty pots left and right # Since the rules only take two pots to left and right into account, # we are guaranteed that adding four pots left and right is sufficient. plants_initial="...."+data[0][15:-1]+"...."# Read and save rules rules={}foriinrange(2,len(data)):rule_match=re.match(r'([#|\.]+) => ([#|\.])',data[i])rule,res=rule_match.group(1),rule_match.group(2)rules[rule]=res# Evolve generations defevolve(generations):plants=list(plants_initial)# Clean start with initial plants seen={}# Keep track of loops when evolving shift=-4# Added padding must be accounted for by shifting e=0# Initial evolve step whilee<generations:e+=1# Evolve step plants_copy=plants.copy()foridx,plantinenumerate(plants):# Ignore outer borders which extend infinitely with empty pots (".") ifidx<2oridx>len(plants)-3:continue# For real inputs all rules are defined. But for example we would # have to use (".") if rule was not defined for this pot. plants_copy[idx]=rules.get(''.join(plants[idx-2:idx+3]),".")ifplants_copy[3]=='#':# If we planted close to the left border, we must extend it: plants_copy.insert(0,'.')shift-=1# Adjusts the pot index shifting elifplants_copy[:5]==['.']*5:# If we have deserted the whole left border, we can remove one pot: plants_copy.remove('.')shift+=1# Adjusts the pot index shifting ifplants_copy[-3]=='#':# If we planted close to the right border, we must extend it: plants_copy.append('.')elifplants_copy[-4:]==['.']*5:# If we have deserted the whole right border, we can remove one pot: plants_copy=plants_copy[:-1]plants=plants_copyifseen.get(''.join(plants),False):# We have made a full circle! No need to recalculate next steps. # We can just warp into the future... circle_length=e-seen[''.join(plants)][0]# The steps of this circle circles=(generations-e)//circle_length# The circles to make e+=circles*circle_length# Warping into future... shift_length=shift-seen[''.join(plants)][1]# The shifts this circle performs shift+=circles*shift_length# Adjusting shifts seen[''.join(plants)]=(e,shift)# Add unseen pattern to dictionary returnplants,shift# Part 1: plants,shift=evolve(generations=20)print('Part 1:')print(sum(i+shiftfori,pinenumerate(plants)ifp=='#'))# Part 2: plants,shift=evolve(generations=50000000000)print('Part 2:')print(sum(i+shiftfori,pinenumerate(plants)ifp=='#'))
Here is the Golang code. I don't think this is the best way of doing it in Golang, but it does the job!
packagemainimport("bufio""fmt""os""reflect""regexp")typeentrystruct{eintshiftint}// readLines reads a whole file into memory// and returns a slice of its lines.funcreadLines(pathstring)([]string,error){file,err:=os.Open(path)iferr!=nil{returnnil,err}deferfile.Close()varlines[]stringscanner:=bufio.NewScanner(file)forscanner.Scan(){lines=append(lines,scanner.Text())}returnlines,scanner.Err()}// function to evolve generations.funcevolve(generationsint)([]rune,int){seen:=make(map[string]entry)shift:=-4plantsCopy:=make([]rune,len(plants))plantsOld:=make([]rune,len(plants))copy(plantsOld,plants)fore:=1;e<=generations;e++{plantsCopy=make([]rune,len(plantsOld))copy(plantsCopy,plantsOld)foridx:=rangeplantsOld{ifidx<2||idx>len(plantsOld)-3{continue}plantsCopy[idx]=rules[string(plantsOld[idx-2:idx+3])]}ifplantsCopy[3]=='#'{plantsCopy=append(plantsCopy,0)copy(plantsCopy[1:],plantsCopy[0:])plantsCopy[0]='.'shift--}elseifreflect.DeepEqual(plantsCopy[:5],[]rune{'.','.','.','.','.'}){plantsCopy=plantsCopy[1:]shift++}ifplantsCopy[len(plantsCopy)-3]=='#'{plantsCopy=append(plantsCopy,'.')}elseifreflect.DeepEqual(plantsCopy[len(plantsCopy)-5:],[]rune{'.','.','.','.','.'}){plantsCopy=plantsCopy[:len(plantsCopy)-1]}ifval,ok:=seen[string(plantsCopy)];ok{circleLength:=e-val.ecircles:=(generations-e)/circleLengthe=e+circles*circleLengthshiftLength:=shift-val.shiftshift=shift+circles*shiftLength}seen[string(plantsCopy)]=entry{e:e,shift:shift}plantsOld=make([]rune,len(plantsCopy))copy(plantsOld,plantsCopy)}returnplantsCopy,shift}varplants[]runevarrulesmap[string]runefuncmain(){data,err:=readLines("input")iferr!=nil{panic(err)}plantsInitial:="...."+data[0][15:]+"...."plants=[]rune(plantsInitial)rules=make(map[string]rune)r,_:=regexp.Compile("([#|\\.]+) => ([#|\\.])")for_,d:=rangedata[2:]{rule:=r.FindStringSubmatch(d)[1]res:=r.FindStringSubmatch(d)[2]rules[rule]=[]rune(res)[0]}// Part 1:plants,shift:=evolve(20)fmt.Println("Part 1:")varsumintsum=0fori,p:=rangeplants{ifp=='#'{sum+=i+shift}}fmt.Println(sum)// Part 2:plants,shift=evolve(50000000000)fmt.Println("Part 2:")sum=0fori,p:=rangeplants{ifp=='#'{sum+=i+shift}}fmt.Println(sum)}
Ryan is an engineer in the Sacramento Area with a focus in Python, Ruby, and Rust. Bash/Python Exercism mentor. Coding, physics, calculus, music, woodworking. Looking for work!
I got part 1 done, but couldn't figure out how I could possibly do that big of a number of generations. So, I peeked (a little) here and, without seeing anyone explicitly giving it away -- but reading enough of the responses to get ideas -- I figured out the trick.
"""Day 12: Subterranean Sustainability Conway's game of life with plants! See which plants will live or die each generation. """fromcollectionsimportdequefromitertoolsimportislicefromtypingimportList,DictclassPlants(deque):"""A row of plants centered around zero"""def__init__(self,*args):deque.__init__(self,*args)self.zero=0defscore(self)->int:"""Sums up all the indices (including negative) that have a plant"""returnsum(i-self.zerofori,potinenumerate(self)ifpot=='#')def__getitem__(self,key)->islice:"""Allows slicing a deque"""ifisinstance(key,slice):returnislice(self,key.start,key.stop,key.step)else:returndeque.__getitem__(self,key)defcopy(self):result=Plants(self)result.zero=self.zeroreturnresultdefnext_generation(plants:Plants,rules:Dict[str,str])->Plants:"""Given a row of pots with/without plants and some rules, creates the next generation of plants. The only rules that could increase the length in either direction require 3 dots on the end to check, so this makes sure there are 3 dots on each end just in case. """this_generation=plants.copy()ifany(c=='#'forcinthis_generation[:3]):this_generation.extendleft(['.']*3)this_generation.zero+=3ifany(c=='#'forcinthis_generation[len(this_generation)-3:]):this_generation.extend(['.']*3)next_generation=this_generation.copy()foriinrange(2,len(this_generation)-2):next_generation[i]=rules.get("".join(this_generation[i-2:i+3]),'.')returnnext_generationdefparse_rules(text:str)->Dict[str,str]:"""Parses the conversion rules from a block of text"""rules={}forlineintext.splitlines():pattern,_,output=line.partition(" => ")rules[pattern]=outputreturnrulesdefage(plants:Plants,generations:int,rules:Dict[str,str])->Plants:"""Ages a set of plants n generations"""foriinrange(generations):plants=next_generation(plants,rules)returnplantsif__name__=="__main__":withopen("python/data/day12.txt","r")asf:rules=parse_rules(f.read())initial_plants=Plants("##..#..##....#..#..#..##.#.###.######..#..###.#.#..##.###.#.##..###..#.#..#.##.##..###.#.#...#.##..")# Part 1 plants=age(initial_plants,20,rules)print(plants.score())# Part 2: Wherein it's #@%!# linear above about 300 plants=age(initial_plants,300,rules)print(plants.score()+(50000000000-300)*86)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Kotlin Solution
This one was similar to a previous year's problem, but it's thankfully in 2d.
Part 1
"Just" make a map of the rules, chunk the input into 5 char seedlings and map them to the rules.
Oh wait... it can grow left and right... better add some padding.
Part 2
This one seemed like it might be hard, but then I realized that part1 was fast enough that I could just do the first couple hundred and watch for loops.
I didn't get a loop, but I did see a consistency! I made a quick function to seek for that and voila! (That's French, for 'voila!')
Bonus Content
Single line:
Multi line:
Actual GIF output from AWT:
EDIT: FORGOT PLANT PUNS:
Um... hopefully this one isn't leaving you out in the weeds?
Er... put the petal to the metal?
Uh... Orange you glad I didn't say banana? (Does fruit count?)
Haha, love your visualisations! Always fascinating how such simple things can create such complexity.
(Slightly off-topic, but I once came across these "meta-pixel" in Conway's Game of Life which literally gave me goose bumps: youtube.com/watch?v=xP5-iIeKXE8)
GET. OUT. This is amazing. Thank you.
Full marks + animations + bonus plant puns! Checking for loops was a good idea. I didn't think of that until I cheated and looked at the discussion here :/
Python.
Part 1
Part 2
Part 1 would be easy for anyone who has ever coded Game of Life (I somehow managed to leave out last line on the input so I spent unreasonable amount of time debugging).
For part 2 after seeing that even 10k generations take a lot I started to look for a pattern and came up with a formula to calculate value for any generation bigger than ~160 (that's when it starts to loop).
php
readFile.php
Part 1 was easy. I used regular expressions to match the rules against the pots, and I needed to keep a record at what position the current pattern starts.
Running it for many more than 20 steps I discovered the pattern stays the same, only moving to the right. So I printed its value for two different numbers, the rest was just two equations:
Ahhh, a one-dimensional Conway's Game of Life.
Part 1 is easy enough - the tricky part is that the space is unbounded. I modelled the row of plants as a boolean array where the first and last are always true (i.e. the left and rightmost plants) and the position of the leftmost plant is stored separately. Thus if the row grows to the right the array gets longer and the origin stays the same, and if it grows to the left the array also gets longer but the origin decreases.
At first I translated the rules into a map of
BooleanArray
toBoolean
but the lookups seemed to have trouble so I converted the five bits of a rule's left hand side to an integer and used that as the key:The use of
&&
and||
for logic andand
andor
for boolean operations in Kotlin seems the wrong way round. Yes you want to bring C / Java programmers with you when you introduce a new language, but in this case I'd have gone for Python's readability.Parsing
Parsing the input data of course uses JParsec. It's just so much easier not to have to deal with questions like "did I find all the parts?" or "does the rule have exactly 5 positions on the left" etc. It either parses or it throws an error and tells you the line and column where the parsing failed.
Part 1
Running one generation of the game involves:
Sequence
so the memory footprint is sequential rather than all at once.Part 1 is just doing that 20 times.
Part 2
At first you read part 2 and think "oh, just up the iteration count to 50 billion".
No.
The secret is that the rules inevitably lead to a repeating pattern. Work out where the loop is, work out how many loops occur in 50 billion iterations, then you only need to run the loop once. The tricky part in this puzzle is that the same pattern of plants may occur with a different origin. Conway's original Game of Life is famous for its walker structures that move across the 2D space, replicating themselves perfectly.
I built a map keyed by a string representation of the plant pattern. When the current state already exists in the map, we have detected a loop. The value stored in the map describes the start of the loop. Then it's just a matter of determining the number of loops, the length of the last incomplete loop (if present), assemble the state at the end of the final loop and finish the sequence. All while avoiding 50 billion opportunities for an off-by-one error.
In my case the loop was only one iteration long, but I suspect that's not true for everyone. My
lastState
calculation's else branch is therefore never taken so I don't have full confidence that's the correct logic.I should also point out I took eight attempts to submit the right answer, constantly tweaking my code before realising I was doing 5 billion iterations, not 50 billion. I should have used the underscore syntax for the big number earlier.
JavaScript solution
I'm gonna omit reader.js which is the same as the other solutions, but you can find it at github.com/themindfuldev/advent-of...
12-common.js
12a.js
12b.js
A python solution.
Here is currently my Python code for today. Took me some time because I did not understand that we had to sum the indeces of the pots(!).
For part 2 I am looking for loops in the evolution, so that if we reach a plant state (regardless of the indeces) that we have reached before, we loop over those same circular steps without recalculation until reaching to the end.
I could clean up a little, especially the code that cleans up the borders. Maybe if I find time I will do it, but I first hope to later make a Golang solution based on my Python code.
Here is the Golang code. I don't think this is the best way of doing it in Golang, but it does the job!
Part B, so sneaky! Part A is uncommented, Part B commented.
I got part 1 done, but couldn't figure out how I could possibly do that big of a number of generations. So, I peeked (a little) here and, without seeing anyone explicitly giving it away -- but reading enough of the responses to get ideas -- I figured out the trick.