亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang 打印數組數組的所有排列

Golang 打印數組數組的所有排列

Go
ibeautiful 2023-02-06 19:40:33
尋找一種方法來打印數組數組的所有組合。數據類型看起來像這樣:// print all combos var data [][]string例子輸入:[[Lorem, Itself], [Alpha, Beta, Theta]]預期輸出:Alpha Alpha、Alpha Beta、Alpha Theta、非常 Alpha、非常 Beta、非常 Theta數組可以是任意長度。完成此任務的最佳方法是什么?
查看完整描述

1 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

我會迭代切片索引的向量。


單索引迭代器:


// Iterator of a slice index. `len` equals to the length of the slice

type 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 iterator

func (i *IdxIter) Reset() {

    i.idx = 0

}


// The index value

func (i IdxIter) Idx() uint {

    return i.idx

}

索引向量的迭代器:


// Index iterator for a slice of slices

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


查看完整回答
反對 回復 2023-02-06
  • 1 回答
  • 0 關注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號