I recently encountered a coding exercise which I solved in python in which I had to port an "algorithm". I don't know how it is called which is why I am describing it: Each new line was a description of the previous line by the amount of the same number printed in sequence and the associated number. Here is an example:
1
11
21
1211
111221
312211
etc
I started learning Go with its channels and concurrency features. So I came back to this exercise to try to solve it more efficiently in parallel with Go. This is what I got so far:
package main
func main() {
channel := make(chan uint8)
go treeCalcRoutine(channel, 0)
channel <- 1
close(channel) //defer is not an option in this case because the channel has
//to be closed before main exits
}
func treeCalcRoutine(in <-chan uint8, generation int) {
if generation > 10 {
return // return after 10 recursive iterations
}
out := make(chan uint8)
defer close(out)
num := uint8(1)
previous := <-i
go treeCalcRoutine(out, generation+1)
for val := range in {
switch {
case val == previous:
num++
default:
num = uint8(1)
out <- num
out <- val
}
previous = val
}
out <- num
out <- previous
}
While trying to debug the program using Delve, I figured out the Program quits without an exception (and exit status 0) while trying to range over an empty/closed channel. I expected the program just to skip the for loop altogether in this case.
I still want to solve this challenge myself so I would appreciate if someone could just point me in the right direction instead of producing a functioning solution. Moreover, please point out any other issues/cases which could be done better (like the generation
limit).
EDIT: Since people asking me to post the error: There is no error at all for some reason. The program just exits once it reaches the for loop.