Skip to content

Instantly share code, notes, and snippets.

@markrickert
Last active August 29, 2015 14:03
Show Gist options
  • Save markrickert/915c9e7d88693604fe19 to your computer and use it in GitHub Desktop.
Save markrickert/915c9e7d88693604fe19 to your computer and use it in GitHub Desktop.
Cartesian Power Example
# Usage
#
[:true, :false].cartesian_power(2) {|l| p l.inspect }
# "[:true, :true]"
# "[:true, :false]"
# "[:false, :true]"
# "[:false, :false]"
#
[:true, :false].cartesian_power(3) {|l| p l.inspect }
# "[:true, :true, :true]"
# "[:true, :true, :false]"
# "[:true, :false, :true]"
# "[:true, :false, :false]"
# "[:false, :true, :true]"
# "[:false, :true, :false]"
# "[:false, :false, :true]"
# "[:false, :false, :false]"
#
[:true, :false].cartesian_power(4) {|l| p l.inspect }
# "[:true, :true, :true, :true]"
# "[:true, :true, :true, :false]"
# "[:true, :true, :false, :true]"
# "[:true, :true, :false, :false]"
# "[:true, :false, :true, :true]"
# "[:true, :false, :true, :false]"
# "[:true, :false, :false, :true]"
# "[:true, :false, :false, :false]"
# "[:false, :true, :true, :true]"
# "[:false, :true, :true, :false]"
# "[:false, :true, :false, :true]"
# "[:false, :true, :false, :false]"
# "[:false, :false, :true, :true]"
# "[:false, :false, :true, :false]"
# "[:false, :false, :false, :true]"
# "[:false, :false, :false, :false]"
class Array
# Credit where credit is due: http://stackoverflow.com/questions/15737065/unique-permutations-for-large-sets/15737305#15737305
def cartesian_power(n)
current = [0] * n
last = [size - 1] * n
loop do
yield current.reverse.collect { |i| self[i] }
break if current == last
(0...n).each do |index|
current[index] += 1
current[index] %= size
break if current[index] > 0
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment