猿问

Golang 打印数组数组的所有排列

寻找一种方法来打印数组数组的所有组合。

数据类型看起来像这样:

// print all combos
var data [][]string

例子

输入:[[Lorem, Itself], [Alpha, Beta, Theta]]

预期输出:Alpha Alpha、Alpha Beta、Alpha Theta、非常 Alpha、非常 Beta、非常 Theta

数组可以是任意长度。完成此任务的最佳方法是什么?


ibeautiful
浏览 202回答 1
1回答

慕的地6264312

我会迭代切片索引的向量。单索引迭代器:// Iterator of a slice index. `len` equals to the length of the slicetype IdxIter struct {    idx uint    len uint}// Returns true is the iteration is over.func (i IdxIter) Done() bool {    return i.idx >= i.len}// Builds the next iteration value. If called for the last index,// the next value's `Done` returns `true`.func (i *IdxIter) Next() {    i.idx++}// Resets the iteratorfunc (i *IdxIter) Reset() {    i.idx = 0}// The index valuefunc (i IdxIter) Idx() uint {    return i.idx}索引向量的迭代器:// Index iterator for a slice of slicestype IdxVectorIter []IdxIter// Returns true is the iteration is over.func (ii IdxVectorIter) Done() bool {    last := len(ii) - 1    return ii[last].Done()}// Builds the next iteration value. If called for the last index vector,// the next value's `Done` returns `true`.func (ii IdxVectorIter) Next() {    if len(ii) == 0 {        return    }    last := len(ii) - 1    for pos := range ii[:last] {        ii[pos].Next()        if ii[pos].Done() {            ii[pos].Reset()        } else {            return        }    }    ii[last].Next()}这样,切片切片的迭代就很简单了:func main() {    words := [][]string{        {"lorem", "ipsum"},        {},        {"Alpha", "Beta", "Gamma"},        {"X", "Y", "Z"},    }    // Fixed buffer for the combinations of words    dst := make([]string, len(words))    // Iteration loop    for ii := NewIdxVectorFromSlices(words); !ii.Done(); ii.Next() {        GetTo(words, dst, ii)        fmt.Printf("%v\n", dst)    }}完整代码https://go.dev/play/p/ecjjcAEexZO输出[lorem  Alpha X][ipsum  Alpha X][lorem  Beta X][ipsum  Beta X][lorem  Gamma X][ipsum  Gamma X][lorem  Alpha Y][ipsum  Alpha Y][lorem  Beta Y][ipsum  Beta Y][lorem  Gamma Y][ipsum  Gamma Y][lorem  Alpha Z][ipsum  Alpha Z][lorem  Beta Z][ipsum  Beta Z][lorem  Gamma Z][ipsum  Gamma Z]
随时随地看视频慕课网APP

相关分类

Go
我要回答