Sha256: a1e34b325a69296b9e9d7b057be3378c29a914d20c3fdcd04993d08ee58d7bfe

Contents?: true

Size: 1.01 KB

Versions: 12

Compression:

Stored size: 1.01 KB

Contents

require 'epitools/basetypes'

class Array
  
  alias_method :"original_*_for_cartesian_*", :*
  def *(other)
    case other
      when Integer
        send(:"original_*_for_cartesian_*", other)
      when Array
        # cross-product
        result = []
        (0...self.size).each do |a|
          (0...other.size).each do |b|
            result << [self[a], other[b]]
          end
        end
        result        
    end
  end
  
  def **(exponent)
    ([self] * exponent).foldl(:*)
  end
  
end

def perms(total, n=0, stack=[], &block)
  ps = yield(n)
  results = []
  if n >= total
    results << stack
  else  
    ps.each do |p|
      results += perms(total, n+1, stack + [p], &block)
    end
  end
  results
end
  

if $0 == __FILE__
  puts "-------------- foldl ---"
  p [:sum, [1,1,1].foldl(:+)]
  p ["[[1,2],[3]].foldl(:+)", [[1,2],[3]].foldl(:+)]
  p [[0,1],[0,1]].foldl(:*)

  puts "-------------- cartesian product ---"
  p ["[0,1]*[2,3]",[0,1]*[2,3]]

  puts "-------------- cartesian exponent ---"
  p [0,1]**3
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
epitools-0.2.1 lib/epitools/permutations.rb
epitools-0.2.0 lib/epitools/permutations.rb
epitools-0.1.11 lib/epitools/permutations.rb
epitools-0.1.10 lib/epitools/permutations.rb
epitools-0.1.9 lib/epitools/permutations.rb
epitools-0.1.8 lib/epitools/permutations.rb
epitools-0.1.6 lib/epitools/permutations.rb
epitools-0.1.5 lib/epitools/permutations.rb
epitools-0.1.4 lib/epitools/permutations.rb
epitools-0.1.3 lib/epitools/permutations.rb
epitools-0.1.2 lib/epitools/permutations.rb
epitools-0.1.1 lib/epitools/permutations.rb