Day 1 in Go

Purely for curiosity/benchmarking-against-identical-Rust-version reasons

Spoilers: Rust is somewhat faster than Go and very much faster than .net
...though presumably .net's problem is purely startup time
This commit is contained in:
2021-12-10 13:46:41 -06:00
parent 21b9ccbfee
commit db06f5b5c6
4 changed files with 80 additions and 0 deletions

1
.gitignore vendored
View File

@ -3,3 +3,4 @@
*.user
/bin/
/obj/
*.exe

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module aoc2021
go 1.17

7
main.go Normal file
View File

@ -0,0 +1,7 @@
package main
import "aoc2021/src"
func main() {
src.Day01()
}

69
src/01.go Normal file
View File

@ -0,0 +1,69 @@
package src
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
)
func Day01() {
fileBytes, fileErr := ioutil.ReadFile("inputs/01.txt")
if fileErr != nil {
panic(fileErr)
}
fileStr := string(fileBytes)
fileLines := strings.Split(strings.ReplaceAll(fileStr, "\r", ""), "\n")
fileInts := make([]int, len(fileLines))
var err error
for idx, line := range fileLines {
fileInts[idx], err = strconv.Atoi(line)
if err != nil {
panic(err)
}
}
part1(fileInts)
part2(fileInts)
}
func part1(depths []int) {
lastDepth := 0
numIncreased := -1
for _, depth := range depths {
if depth > lastDepth {
numIncreased++
}
lastDepth = depth
}
fmt.Println("part1: increased:", numIncreased)
}
func part2(depths []int) {
lastTotal := 0
numIncreased := -1
num1 := -1
num2 := -1
num3 := -1
for _, depth := range depths {
num1 = num2
num2 = num3
num3 = depth
if num1 < 0 || num2 < 0 || num3 < 0 {
continue
}
total := num1 + num2 + num3
if total > lastTotal {
numIncreased++
}
lastTotal = total
}
fmt.Println("part2: increased:", numIncreased)
}