re: AoC Day 1: Chronal Calibration VIEW POST

FULL DISCUSSION
 

Golang solution

Part 1

package main

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

func freq(f *os.File)(sum int) {
    scanner := bufio.NewScanner(f)
    for scanner.Scan() {
        i, err := strconv.Atoi(scanner.Text())
        if err != nil {
            panic(err)
        }
        sum += i
    }
    return
}

func main() {
    f, err := os.Open("input1.txt")
    if err != nil {
        panic(err)
    }
    freq(f)
}

Part 2

package main

import (
    "io/ioutil"
    "strconv"
    "container/ring"
    "strings"
)

func dup(x string)(sum int) {
    list := strings.Split(x, "\n")
    r := ring.New(len(list))
    seen := map[int]bool{0: true}
    for i := 0; i < r.Len(); i++ {
        num, err := strconv.Atoi(list[i])
        if err != nil {
            panic(err)
        }
        r.Value = num
        r = r.Next()
    }
    for true {
        sum += r.Value.(int)
        if (seen[sum] == true) {
            return sum
        }
        seen[sum] = true
        r = r.Next()
    }
    return
}

func main() {
    f, err := ioutil.ReadFile("input1.txt")
    if err != nil {
        panic(err)
    }
    dup(string(f))
}

I also wrote solutions in Python that look very similar to Ali's, so I decided to run a little benchmark test using today's input from the Advent of Code website. Here are the results

`python3 1_1.py` 100 times
real    0m4.261s
user    0m2.845s
sys 0m0.936s

`go run 1_1.go` 100 times
real    0m34.169s
user    0m26.057s
sys 0m13.171s

go build 1_1.go

`./1_1` 100 times
real    0m0.641s
user    0m0.216s
sys 0m0.253s

`python3 1_2.py` 100 times
real    0m8.347s
user    0m6.126s
sys 0m1.477s

`go run 1_2.go` 100 times
real    0m38.925s
user    0m31.556s
sys 0m14.668s

go build 1_2.go

`./1_2` 100 times
real    0m3.891s
user    0m3.067s
sys 0m0.657s
 

Woah, nice! Am I reading this right, that the Python is significantly faster than Go? Or is this including compilation each time?

 

Python is significantly faster than running go run myfile.go. However, that's not Go's intended use case, really. That's more for debugging along the way, since go run does include the compilation each time.

I think it's interesting to compare the difference between go run and executing the compiled go executable, so the third set of each (ex: ./1_1) is go running the resulting compiled executable 100 times.

 

Also, I am not a regular Go programmer. I've started doing challenges in Go just for my own amusement, but I would definitely not assume that whatever solution I come up with is optimal 😅

Hi jess!

Just a small advert: you should defer f.Close() after check if there's an error.

Also: Check out my GitHub Repo.

Oh, if this were production code I totally would, but I'm really only building these solutions to solve the problem, and not looking to make them infinitely extensible.

code of conduct - report abuse