package main import( "fmt" "time" "runtime" ) var resultc chan comb var maxsum int = 660 var endch chan int var routinelimit chan bool func main(){ routinelimit = make(chan bool, 5000) for i := 0; i < 10; i++ { routinelimit <- true } go func() { for { routinelimit <- true time.Sleep(1 * time.Millisecond) } }() endch = make(chan int, 1) resultc = make(chan comb, 30) input := make(comb, 0, 0) input = append(input, 30, 40, 20, 10, 50, 200, 300, 100, 20, 60) go getter() things := make(comb, 0, 0) go reccombinator(things, input) <- endch } func getter() { for { res := <- resultc str := "Res: " for _, val := range res { str += fmt.Sprint(val) + ", " } str += "Sum: " + fmt.Sprint(res.sum()) fmt.Println(str) } } func reccombinator(things comb, input comb) { <- routinelimit if things.sum() == maxsum { } else if things.sum() > maxsum { return } else { successes := 0 for _, val := range input { newthings := make(comb, len(things)) copy(newthings, things) newinput := make(comb, len(input)) copy(newinput, input) newthings = append(newthings, val) newinput.remove(val) if newthings.sum() <= maxsum { successes++ possible := false for _, i := range newinput { sum := newthings.sum() if sum + i < maxsum { possible = true } else if sum + i == maxsum { } } if possible { go reccombinator(newthings, newinput) } else { resultc <- newthings } } } } runtime.Gosched() runtime.GC() } type comb []int func (c comb) sum() int { mysum := 0 for _, val := range c { mysum += val } return mysum } func (c comb) remove(i int) comb { for index, val := range c { if val == i { c = append(c[:index], c[index+1:]...) //a = append(a[:i], a[i+1:]...) return c } } return c }