I am using Advent of Code to learn Golang, and here is the solution I came up with. Suggestions for improvements are always welcome!
Part 1:
packagemainimport("bufio""fmt""os""strconv")// readLines reads a whole file into memory// and returns a slice of its lines.funcreadLines(pathstring)([]int,error){file,err:=os.Open(path)iferr!=nil{returnnil,err}deferfile.Close()varlines[]intscanner:=bufio.NewScanner(file)forscanner.Scan(){// string to inti,err:=strconv.Atoi(scanner.Text())iferr!=nil{returnnil,err}lines=append(lines,i)}returnlines,scanner.Err()}funcmain(){lines,err:=readLines("input")iferr!=nil{panic(err)}varsumintfor_,line:=rangelines{sum+=line}fmt.Printf("Sum is: %d\n",sum)}
Part 2:
packagemainimport("bufio""fmt""os""strconv")// readLines reads a whole file into memory// and returns a slice of its lines.funcreadLines(pathstring)([]int,error){file,err:=os.Open(path)iferr!=nil{returnnil,err}deferfile.Close()varlines[]intscanner:=bufio.NewScanner(file)forscanner.Scan(){// string to inti,err:=strconv.Atoi(scanner.Text())iferr!=nil{returnnil,err}lines=append(lines,i)}returnlines,scanner.Err()}funcmain(){lines,err:=readLines("input")iferr!=nil{panic(err)}occurences:=map[int]int{0:1}varfreq,jintforoccurence:=1;occurence<2;j++{freq+=lines[j%len(lines)]_,ok:=occurences[freq]ifok{occurence=2}occurences[freq]=1}fmt.Printf("%d\n",freq)}
I am also using Python that I have more experience with to cross check solutions.
I am using Advent of Code to learn Golang, and here is the solution I came up with. Suggestions for improvements are always welcome!
Part 1:
Part 2:
I am also using Python that I have more experience with to cross check solutions.
Part 1:
Part 2