Last year I decided I would try advent of code, solved the first two days and then sort of gave up.
This year will be different™️!
All cmd/puzzleXX directories are their own main
package. Luckily Go is smart (apparently) and you can just cd into those directories and go run .
and everything is scoped to that directory. I was a little worried that puzzle01::parseLine would leak into the main package of puzzle02, but it doesn't.
I'm pretty sure this is not how you're supposed to do things but the point was to learn, and this works for now. I'll refactor if I have to but it's AoC, not a production application.
Except it sort of does:
x := 0
for x < 5 {
fmt.Println(x)
x++
}
The trick when spawning multiple threads is to use waitgroups
package main
import (
"fmt"
"sync"
"time"
)
func processElement(waitTime int, resultChan chan int, wg *sync.WaitGroup) {
defer wg.Done() // `defer` means wg.Done() gets called when the function exits
time.Sleep(time.Duration(waitTime) * time.Second)
resultChan <- waitTime
}
func main() {
resultChan := make(chan int)
var wg sync.WaitGroup
// This behaves like a loop of sleep(time.Second) calls but is actually parallel
for i := 0; i < 5; i++ {
wg.Add(1)
go processElement(i, resultChan, &wg)
}
go func() {
wg.Wait()
close(resultChan)
}()
for result := range resultChan {
// This will loop until you close the channel - which happens when the wg is done
fmt.Println(result)
}
}
// someSlice is of type []int
someSlice = append([]int{1337}, someSlice...)
Also, you can't append a slice to a slice. What you can do is this:
// someSlice and someOtherSlices are the same type []T
joinedSlices := append(someSlice, someOtherSlice...)
As long as both slices contain the same type you're good to go