SO,
The problem
From SQL I\'m getting an array with strings (flat array) - let it be
$rgData = [\'foo\', \'bar\', \'baz\', \'bee\
I've just tried to solve this problem with minimum time complexity and without using recursion using go language.
I've seen a few solutions, but with using a recursive function. Avoiding recursion to solve stack size exceeded error.
package main
import "fmt"
func main() {
// Arguments
arr := []string{"foo", "bar", "baz", "bee", "feo", "boo", "bak"}
combinations := make([][]string, 0)
k := 4
n := len(arr)
// Execution starts from here
if k > n {
panic("invalid requirement")
}
pos := make([]int, k) // this variable is used to plot the unique combination of elements
// initialize an array with first ever plotting possitions
i := 0
c := k
for c > 0 {
c--
pos[i] = c
i++
}
combinations = append(combinations, getCombination(arr, pos, k))
// Let's begin the work
x := 0
ctr := 1 // counter is use to calculate total iterations
for pos[x] < n-(x+1) {
ctr++
pos[x]++
combinations = append(combinations, getCombination(arr, pos, k))
if pos[x] == n-(x+1) && x+1 < k {
x++
i := x
s := pos[x] + 1
for i > 0 {
i--
s++
pos[i] = s
}
// continue to next index
continue
}
x = 0
}
fmt.Println("total # iterations: --> ", ctr)
fmt.Println(combinations, "\ntotal # combinations: ", len(combinations))
}
func getCombination(arr []string, pos []int, k int) []string {
combination := make([]string, k)
for i, j := k-1, 0; i >= 0; i, j = i-1, j+1 {
combination[j] = arr[pos[i]]
}
return combination
}
The working example is here https://play.golang.org/p/D6I5aq8685-