### re: AoC Day 1: Chronal Calibration VIEW POST

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:

``````package main

import (
"bufio"
"fmt"
"os"
"strconv"
)

// and returns a slice of its lines.
func readLines(path string) ([]int, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()

var lines []int
scanner := bufio.NewScanner(file)
for scanner.Scan() {
// string to int
i, err := strconv.Atoi(scanner.Text())
if err != nil {
return nil, err
}
lines = append(lines, i)
}
return lines, scanner.Err()
}

func main() {
if err != nil {
panic(err)
}

var sum int
for _, line := range lines {
sum += line
}
fmt.Printf("Sum is: %d\n", sum)
}
``````

Part 2:

``````package main

import (
"bufio"
"fmt"
"os"
"strconv"
)

// and returns a slice of its lines.
func readLines(path string) ([]int, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()

var lines []int
scanner := bufio.NewScanner(file)
for scanner.Scan() {
// string to int
i, err := strconv.Atoi(scanner.Text())
if err != nil {
return nil, err
}
lines = append(lines, i)
}
return lines, scanner.Err()
}

func main() {
if err != nil {
panic(err)
}

occurences := map[int]int{0: 1}
var freq, j int
for occurence := 1; occurence < 2; j++ {
freq += lines[j%len(lines)]
_, ok := occurences[freq]
if ok {
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.

Part 1:

``````def chronal_calibration(fname):
with open(fname) as f:
return sum([int(x.strip()) for x in content])

chronal_calibration('input')
``````

Part 2

``````import itertools

def chronal_calibration_cycle(fname):
with open(fname) as f:
content = [int(x.strip()) for x in content]
freq = 0
occurences = {freq: 1}
for change in itertools.cycle(content):
freq += change
occurences[freq] = occurences.get(freq, 0) + 1
if occurences[freq] > 1:
break
return freq

print(chronal_calibration_cycle('input'))
``````
code of conduct - report abuse