获取切片的所有排列

时间:2013-04-25 19:17:25

标签: go permutation

我想知道是否有办法找到在Go中填充字符的切片的所有排列?

在Python中,您可以将itertools.product与列表或字符或整数一起使用,您可以获得所有可能的排列。

我已经看过那里是否有包裹,我似乎找不到一个。任何帮助都会受到欢迎。

3 个答案:

答案 0 :(得分:9)

实施sort.Interface的任何内容的排列:Permutation{First,Next}

答案 1 :(得分:0)

这是我编写的排列函数的实现......

https://github.com/itcraftsman/GoPermutation

func permutate(slice [][]int) (permutations [][][]int){
    f := fac(len(slice))
    for i := 0; i < len(slice); i++ {
        elem, s := splice(slice, i)
        pos := 0
        for count := 0; count < (f / len(slice)); count++{
            if pos == (len(s) -1) {
                pos = 0
            }
            s = swap(s, pos, pos +1)
            permutation := make([][]int, len(slice))
            permutation = s
            permutation = append(permutation, elem)
            permutations = append(permutations, permutation)
            pos++
        } 
    } 
    return
}

它将2D切片作为输入并返回3D切片,但您可以轻松更改代码,以便该函数将一个简单切片作为输入并返回具有所有排列的2D切片

答案 2 :(得分:0)

不确定这是否能解答您的问题,但这是一个简单的递归实现,可以找到下面的输出。

package main

import "fmt"

func main() {
    values := [][]int{}

    // These are the first two rows.
    row1 := []int{1, 2, 3}
    row2 := []int{4, 5, 6}
    row3 := []int{7, 8, 9}

    // Append each row to the two-dimensional slice.
    values = append(values, row1)
    values = append(values, row2)
    values = append(values, row3)


    fmt.Println(getPermutation(values))
}

func getPermutation(vids [][]int) [][]int {
    toRet := [][]int{}

    if len(vids) == 0 {
      return toRet
    }

    if len(vids) == 1 {
        for _, vid := range vids[0] {
            toRet = append(toRet, []int{vid})
        }
        return toRet
    }

    t := getPermutation(vids[1:])
    for _, vid := range vids[0] {
        for _, perm := range t {
            toRetAdd := append([]int{vid}, perm...)
            toRet = append(toRet, toRetAdd)
        }
    }

    return toRet
}

https://play.golang.org/p/f8wktrxkU0

上述代码段的输出:

[[1 4 7] [1 4 8] [1 4 9] [1 5 7] [1 5 8] [1 5 9] [1 6 7] [1 6 8] [1 6 9] [2 4 7] [2 4 8] [2 4 9] [2 5 7] [2 5 8] [2 5 9] [2 6 7] [2 6 8] [2 6 9] [3 4 7] [3 4 8] [3 4 9] [3 5 7] [3 5 8] [3 5 9] [3 6 7] [3 6 8] [3 6 9]]
相关问题