I am using Advent of Code to learn Golang, and here is the solution I came up with. Suggestions for improvements are always welcome!
I was first using a list which would go from left to right and remove pairs as they were found reacting, shifting one step to the left and continue finding pairs that react. However, this could be simplified by using Ali Spittel's stack solution in Python.
With this inspiration, here is my Golang solution. I have added timing functions just to print out the running time as I have compared them to Python it is finally a speed up using Golang for the solution in this case!
packagemainimport("bufio""fmt""os""strings""time""unicode")// 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()}funcinvertChar(crune)rune{ifunicode.ToUpper(c)==c{returnunicode.ToLower(c)}returnunicode.ToUpper(c)}funcreact(polymerstring)int{stack:=[]rune{}vartoprunefor_,unit:=rangepolymer{iflen(stack)==0{// Initialise stack:stack=append(stack,unit)continue}top=stack[len(stack)-1]iftop==invertChar(unit){// Consume last unit:stack=stack[:len(stack)-1]}else{stack=append(stack,unit)}}returnlen(stack)}funcmain(){data,err:=readLines("input")iferr!=nil{panic(err)}polymerString:=data[0]// Part 1start:=time.Now()fmt.Println(react(polymerString))elapsed:=time.Since(start)fmt.Println(elapsed)// Part 2:start=time.Now()varreducedstringminReact:=-1charSet:="ABCDEFGHIJKLMNOPQRSTUVXYZ"for_,c:=rangecharSet{reduced=strings.Replace(polymerString,string(c),"",-1)reduced=strings.Replace(reduced,string(unicode.ToLower(c)),"",-1)r:=react(reduced)ifminReact==-1||r<minReact{minReact=r}}fmt.Println(minReact)elapsed=time.Since(start)fmt.Println(elapsed)}
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 am using Advent of Code to learn Golang, and here is the solution I came up with. Suggestions for improvements are always welcome!
I was first using a list which would go from left to right and remove pairs as they were found reacting, shifting one step to the left and continue finding pairs that react. However, this could be simplified by using Ali Spittel's stack solution in Python.
With this inspiration, here is my Golang solution. I have added timing functions just to print out the running time as I have compared them to Python it is finally a speed up using Golang for the solution in this case!
Nice!