Combinations can be printed using the following recursive code (inspired from Rosetta)
I thought it would be easy to store the intermediate results in an []int or the set of combination in an [][]int. But, because the function is recursive, it is not so easy than replacing the
fmt.Println(s)
by a
return s
with a minor modification of the function output for example. I also tried to feed a pointer like
p *[][]int
with the variable "s" inside the recursive function, but I failed :-/
I think it is a general problem with recursive functions so if you have some advises to solve this problem it will help me a lot !
Many thanks in advance ! ;)
package main
import (
"fmt"
)
func main() {
comb(5, 3)
}
func comb(n, m int) {
s := make([]int, m)
last := m - 1
var rc func(int, int)
rc = func(i, next int) {
for j := next; j < n; j++ {
s[i] = j
if i == last {
fmt.Println(s)
} else {
rc(i+1, j+1)
}
}
return
}
rc(0, 0)
}