Anonymous user
Power set: Difference between revisions
→{{header|Ruby}}
Line 1,773:
<lang ruby># Based on http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/
# See the link if you want a shorter version. This was intended to show the reader how the method works.
class Array
# Adds a power_set method to every array, i.e.: [1, 2].power_set
def power_set
# Injects into a blank array of arrays.
Line 1,781:
# you is each element of the array
inject([[]]) do |acc, you|
ret = [] # Set up a new array to add into
ret << i # Add itself into the new array▼
ret << i + [you] # Merge the array with a new array of the current element▼
▲ # Add itself into the new array
▲ # Merge the array with a new array of the current element
end
ret # Return the array we're looking at to inject more.▼
▲ # Return the array we're looking at to inject more.
end
end
# A more functional and even clearer variant.
def func_power_set
Line 1,812 ⟶ 1,801:
#A direct translation of the "power array" version above
require 'set'
class Set
end
end
end
p [1,2,3,4].power_set
p %w(one two three).func_power_set
p Set[1,2,3].powerset</lang>
{{out}}
<pre>
[[], [4], [3], [3, 4], [2], [2, 4], [2, 3], [2, 3, 4], [1], [1, 4], [1, 3], [1, 3, 4], [1, 2], [1, 2, 4], [1, 2, 3], [1, 2, 3, 4]]
[[], ["one"], ["two"], ["one", "two"], ["three"], ["one", "three"], ["two", "three"], ["one", "two", "three"]]
#<Set: {#<Set: {}>, #<Set: {1}>, #<Set: {2}>, #<Set: {1, 2}>, #<Set: {3}>, #<Set: {1, 3}>, #<Set: {2, 3}>, #<Set: {1, 2, 3}>}>
</pre>
=={{header|Scala}}==
|