2013-04-25 33 views
5

我想知道是否有一種方法可以找到在Go中充滿字符的切片的所有排列組合?獲取切片的所有排列

在Python中,您可以使用帶有一個或多個字符或整數的itertools.product,並且可以獲得所有可能的排列。

我看過看看有沒有一個包,我似乎無法找到一個。任何幫助將受到歡迎。任何事物

+2

'itertools.product'給你一些套笛卡爾乘積。它不*給你排列。雖然你可以使用笛卡爾產品來計算排列,但這會非常低效。 http://docs.python.org/2/library/itertools.html#itertools.product – scvalex 2013-04-25 19:19:57

+0

我是個白癡。我總是把這些混在一起,我找到了一個Cartesian產品的包裝。謝謝 – Colum 2013-04-25 19:22:04

+1

@Colum你犯了一個錯誤;這不會讓你成爲一個白癡。 – 2013-04-25 20:31:33

回答

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 
} 

它需要一個二維切片作爲輸入,返回一個3D切片,但您可以輕鬆更改代碼,以便該功能將採用簡單的切片作爲輸入並返回所有排列的2D切片

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]]