Get possible array combinations

后端 未结 3 2065
悲&欢浪女
悲&欢浪女 2021-01-01 00:05

SO,

The problem

From SQL I\'m getting an array with strings (flat array) - let it be

$rgData = [\'foo\', \'bar\', \'baz\', \'bee\         


        
3条回答
  •  自闭症患者
    2021-01-01 00:25

    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-

提交回复
热议问题