Goに文字が入っているスライスのすべての順列を見つける方法があるのだろうか?スライスのすべての順列を取得
Pythonでは、itertools.product
にリストまたは文字または整数を使用できます。可能なすべての置換を得ることができます。
私はそこにパッケージがあるかどうかを調べましたが、見つけられないようです。どんな援助も歓迎されるだろう。 sort.Interface
を実装何の
Goに文字が入っているスライスのすべての順列を見つける方法があるのだろうか?スライスのすべての順列を取得
Pythonでは、itertools.product
にリストまたは文字または整数を使用できます。可能なすべての置換を得ることができます。
私はそこにパッケージがあるかどうかを調べましたが、見つけられないようです。どんな援助も歓迎されるだろう。 sort.Interface
を実装何の
は私が書いた置換関数の実装です...
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スライスを返すようにコードを簡単に変更できます
これがあなたの質問に答えるかどうかは分かりませんが、これは以下の出力を見つけるための単純な再帰的実装です。
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
私はばかです。私はいつもそれらが混ざるようにし、私はデカルト製品のパッケージを見つけました。ありがとう – Colum
@Columあなたは間違いを犯しました。それはあなたを馬鹿にしません。 –