Created
June 5, 2012 05:43
-
-
Save mduvall/2872911 to your computer and use it in GitHub Desktop.
k-subset generation example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def subsets(s, k) | |
max = 1 << s.length | |
allsubsets = [] | |
(0..max).each do |i| | |
subset = [] | |
ii = i | |
index = 0 | |
while ii > 0 | |
if ii & 1 > 0 | |
subset << s[index] | |
end | |
ii >>= 1 | |
index += 1 | |
end | |
allsubsets << subset if subset.length == k | |
end | |
allsubsets | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty straight forward, generate all binary strings of
s.length
and iteratively check each number of k elements.