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

aside section._1OhGeD · · 881 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

  • 用途描述:一组数组 [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

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:aside section._1OhGeD

查看原文:Golang 数组穷举所有组合(不交叉顺序)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

881 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传