I'm trying to get a code to work that pretty much involves channels in goroutine (in a yield-like behavior in C#)
The code involves getting an iterable matrix from a slice like so:
elements := []float64{1, 2, 3, 4}
expected := [][]float64{
{1},
{2},
{3},
{4},
{1, 2},
{1, 3},
{2, 3},
{1, 4},
{2, 4},
{3, 4},
{1, 2, 3},
{1, 2, 4},
{1, 3, 4},
{2, 3, 4},
{1, 2, 3, 4},
}
I've tried applying Knuth's by doing:
func Combinadic(values []float64) <-chan []float64 {
ch := make(chan []float64)
go func() {
for i := 0; i < len(values); i++ {
for value := range CombinadicK(values, i+1) {
ch <- value
}
}
close(ch)
}()
return ch
}
func CombinadicK(values []float64, k int) <-chan []float64 {
chnl := make(chan []float64)
go func() {
n := len(values)
t := k
c := make([]int, t+3)
current := make([]float64, t)
x := 0
j := 0
for j = 1; j <= t; j++ {
c[j] = j - 1
}
c[t+1] = n
c[t+2] = 0
j = t
for {
for i := 0; i < len(current); i++ {
current[i] = values[c[i+1]]
}
chnl <- current
if j > 0 {
x = j
} else {
if c[1]+1 < c[2] {
c[1]++
continue
} else {
j = 2
}
}
for {
c[j-1] = j - 2
x = c[j] + 1
if x == c[j+1] {
j++
} else {
break
}
}
c[j] = x
j--
if j >= t {
break
}
}
close(chnl)
}()
return chnl
}
It appears to give out random number per row, but the structure of the expected (the count of items per row) appears to be ok.
The code in Go Playground