Skip to content

Instantly share code, notes, and snippets.

@Beyarz
Last active January 1, 2025 18:07
Show Gist options
  • Save Beyarz/9970ddd53774d8e4739d682f679cd362 to your computer and use it in GitHub Desktop.
Save Beyarz/9970ddd53774d8e4739d682f679cd362 to your computer and use it in GitHub Desktop.
Calculate power set from an array
arr = [1, 2, 3]
# => [1, 2, 3]
def power_set(arr)
result = [[]]
arr.each do |element|
result += result.map do |num|
num + [element]
end
end
result
end
# => :power_set
power_set(arr)
# => [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
@Beyarz
Copy link
Author

Beyarz commented Jan 1, 2025

class Array
   def power_set
    total = [[]]
     self.each do |element|
      total += total.map do |num|
         num += [element]
       end
     end
     total
   end
end

[1, 2, 3].power_set
# => [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

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