2017-07-31 43 views
2

我正在Ruby中實現遞歸powerset算法,並且遇到了this Stack Overflow帖子。瞭解按位OR'|'在Ruby示例中

def powerset(set) 
    return [set] if set.empty? 

    p = set.pop 
    subset = powerset(set) 
    subset | subset.map { |x| x | [p] } 
end 

powerset(['a'], ['b'], ['c']) ---> [[], ["a"], ["b"], ["a", "b"], ["c"], ["a", "c"], ["b", "c"], ["a", "b", "c"]]

基本上,我是在理解的最後一行的損失。我明白這是'bitwise or'運營商,我通常明白這是幹什麼用的,但是我在理解這條最後一行的工作原理時遇到了很多麻煩。

有人可以告訴我什麼相當容易閱讀Ruby嗎?

+5

實際上等同|'是['union'運營商(https://ruby-doc.org/core- 2.2.0/Array.html#method-i-7C) – Hamms

+1

Ruby的操作符總是解決方法。如果接收者是一個整數,那麼['|'](http://ruby-doc.org/core-2.4.1/Integer.html#method-i-7C)是按位或。但對於數組,它是聯合。 – Stefan

+0

如果你能告訴我們,'Set#|'的文檔中的哪些*特定*部分對你來說是不清楚的。這樣,Ruby開發人員可以爲未來的讀者改進文檔。 –

回答

1

這裏陣列上,`使用時,在易於閱讀的話:)

If the set is empty: 
    return a list with one empty set 

Remove an element from the set and call it "p" 
Call "subset" the powerset of the new set (that excludes p) 
Return the union of this new powerset and another 
    version of it, where p is added to each of its sets