Skip to content

Instantly share code, notes, and snippets.

@woodRock
Created September 17, 2018 11:18
Show Gist options
  • Save woodRock/e111925868f99e4503a2e25009352fce to your computer and use it in GitHub Desktop.
Save woodRock/e111925868f99e4503a2e25009352fce to your computer and use it in GitHub Desktop.
The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set. For example, given the set {1, 2, 3}, it should return {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}.
#!/usr/bin/env ruby
def power_set(set)
size = set.size() ** 2
size.times do |counter|
size.times do |j|
if ((counter & (1 << j)) > 0)
print set[j]
end
end
print "\n"
end
end
set = ['A','B','C']
power_set(set)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment