我想知道是否有一种方法可以找到在Go中充满字符的切片的所有排列组合?获取切片的所有排列
在Python中,您可以使用带有一个或多个字符或整数的itertools.product
,并且可以获得所有可能的排列。
我看过看看有没有一个包,我似乎无法找到一个。任何帮助将受到欢迎。任何事物
我想知道是否有一种方法可以找到在Go中充满字符的切片的所有排列组合?获取切片的所有排列
在Python中,您可以使用带有一个或多个字符或整数的itertools.product
,并且可以获得所有可能的排列。
我看过看看有没有一个包,我似乎无法找到一个。任何帮助将受到欢迎。任何事物
这里是一个置换函数我写的实现......
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切片
不确定这是否回答你的问题,但这是一个简单的递归实现来找到下面的输出。
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]]
'itertools.product'给你一些套笛卡尔乘积。它不*给你排列。虽然你可以使用笛卡尔产品来计算排列,但这会非常低效。 http://docs.python.org/2/library/itertools.html#itertools.product – scvalex 2013-04-25 19:19:57
我是个白痴。我总是把这些混在一起,我找到了一个Cartesian产品的包装。谢谢 – Colum 2013-04-25 19:22:04
@Colum你犯了一个错误;这不会让你成为一个白痴。 – 2013-04-25 20:31:33