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)}
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.
Here is the Golang code. I don't think this is the best way of doing it in Golang, but it does the job!