Skip to content

Instantly share code, notes, and snippets.

@mduvall
Created June 5, 2012 05:43
Show Gist options
  • Save mduvall/2872911 to your computer and use it in GitHub Desktop.
Save mduvall/2872911 to your computer and use it in GitHub Desktop.
k-subset generation example
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
@mduvall
Copy link
Author

mduvall commented Jun 5, 2012

Pretty straight forward, generate all binary strings of s.length and iteratively check each number of k elements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment