本文簡要介紹ruby語言中 Array.repeated_combination
的用法。
用法
repeated_combination(n) {|combination| ... } → self
repeated_combination(n) → new_enumerator
使用 self
的元素的長度 n
的每個重複組合調用塊;每個組合都是一個數組;返回 self
。組合的順序是不確定的。
當給出一個塊和一個正整數參數 n
時,調用帶有每個 n
-tuple 重複組合 self
元素的塊。組合數為 (n+1)(n+2)/2
。
n
= 1:
a = [0, 1, 2]
a.repeated_combination(1) {|combination| p combination }
輸出:
[0]
[1]
[2]
n
= 2:
a.repeated_combination(2) {|combination| p combination }
輸出:
[0, 0]
[0, 1]
[0, 2]
[1, 1]
[1, 2]
[2, 2]
如果n
為零,則使用空數組調用塊一次。
如果n
為負數,則不調用該塊:
a.repeated_combination(-1) {|combination| fail 'Cannot happen' }
如果沒有給出塊,則返回一個新的枚舉器:
a = [0, 1, 2]
a.repeated_combination(2) # => #<Enumerator: [0, 1, 2]:combination(2)>
使用枚舉器,可以方便地顯示 n
的某些值的組合和計數:
e = a.repeated_combination(0)
e.size # => 1
e.to_a # => [[]]
e = a.repeated_combination(1)
e.size # => 3
e.to_a # => [[0], [1], [2]]
e = a.repeated_combination(2)
e.size # => 6
e.to_a # => [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
相關用法
- Ruby Array.repeated_combination()用法及代碼示例
- Ruby Array.repeated_permutation()用法及代碼示例
- Ruby Array.repeated_permutation用法及代碼示例
- Ruby Array.replace()用法及代碼示例
- Ruby Array.replace用法及代碼示例
- Ruby Array.reject!用法及代碼示例
- Ruby Array.reject用法及代碼示例
- Ruby Array.reverse用法及代碼示例
- Ruby Array.reverse!用法及代碼示例
- Ruby Array.reverse_each用法及代碼示例
- Ruby Array.rassoc(obj)用法及代碼示例
- Ruby Array.rotate()用法及代碼示例
- Ruby Array.rindex用法及代碼示例
- Ruby Array.rotate!用法及代碼示例
- Ruby Array.rassoc用法及代碼示例
- Ruby Array.rrindex()用法及代碼示例
- Ruby Array.rotate用法及代碼示例
- Ruby Array.rassoc()用法及代碼示例
- Ruby Array.push用法及代碼示例
- Ruby Array.hash用法及代碼示例
- Ruby Array.to_a用法及代碼示例
- Ruby Array.to_h用法及代碼示例
- Ruby Array.to_s用法及代碼示例
- Ruby Array.array + other_array用法及代碼示例
- Ruby Array.take()用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Array.repeated_combination。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。