美文网首页Go语言实践Go
Golang 数组穷举所有组合(不交叉顺序)

Golang 数组穷举所有组合(不交叉顺序)

作者: 承诺一时的华丽 | 来源:发表于2019-10-30 09:36 被阅读0次
    • 用途描述:一组数组 [1, 2, 3],需计算出该数组所有不交叉顺序的组合

    [1]
    [2]
    [3]
    [1,2]
    [2,3]
    [1,3]
    [1,2,3]

    • 穷举算法
    func getArrayExhaustivity(arr []string) (result [][]string) {
        var l = int(math.Pow(float64(2), float64(len(arr))) - 1)
        var t []string
        for i := 1; i <= l; i++ {
            s := i
            t = []string{}
            for k := 0; s > 0; k++ {
                if s&1 == 1 {
                    t = append(t, arr[k])
                }
                s >>= 1
            }
            result = append(result, t)
        }
        return
    }
    
    • 示例代码1
    func TestArrayExhaustivity(t *testing.T) {  
        result := getArrayExhaustivity([]string{"1", "2", "3"})
        str, err := json.Marshal(result)
        if err != nil {
            t.Fatal(err)
        }
        println(string(str))
    }
    
    • 示例结果1
    === RUN   TestArrayExhaustivity
    [["1"],["2"],["1","2"],["3"],["1","3"],["2","3"],["1","2","3"]]
    --- PASS: TestArrayExhaustivity (0.00s)
    PASS
    
    Process finished with exit code 0
    
    • 示例代码2
    func TestArrayExhaustivity(t *testing.T) {
        result := getArrayExhaustivity([]string{"1", "2", "3", "4"})
        str, err := json.Marshal(result)
        if err != nil {
            t.Fatal(err)
        }
        println(string(str))
    }
    
    • 示例结果2
    === RUN   TestArrayExhaustivity
    [["1"],["2"],["1","2"],["3"],["1","3"],["2","3"],["1","2","3"],["4"],["1","4"],["2","4"],["1","2","4"],["3","4"],["1","3","4"],["2","3","4"],["1","2","3","4"]]
    --- PASS: TestArrayExhaustivity (0.00s)
    PASS
    
    Process finished with exit code 0
    
    • 根据长度冒泡排序
    func arrayLenSort(result [][]string) [][]string {
        for i := 0; i < len(result); i++ {
            for j := i + 1; j < len(result); j++ {
                if len(result[i]) < len(result[j]) {
                    tmp := result[i]
                    result[i] = result[j]
                    result[j] = tmp
                }
            }
        }
        return result
    }
    
    • 示例代码3
    func TestArrayExhaustivitySort(t *testing.T) {
        result := getArrayExhaustivity([]string{"1", "2", "3", "4"})
        result = arrayLenSort(result)
        str, err := json.Marshal(result)
        if err != nil {
            t.Fatal(err)
        }
        println(string(str))
    }
    
    • 示例结果3
    === RUN   TestArrayExhaustivitySort
    [["1","2","3","4"],["1","2","4"],["1","3","4"],["2","3","4"],["1","2","3"],["2","4"],["1","3"],["3","4"],["2","3"],["1","2"],["1","4"],["4"],["2"],["1"],["3"]]
    --- PASS: TestArrayExhaustivity (0.00s)
    PASS
    
    Process finished with exit code 0
    

    相关文章

      网友评论

        本文标题:Golang 数组穷举所有组合(不交叉顺序)

        本文链接:https://www.haomeiwen.com/subject/ihanvctx.html