Skip to content

Instantly share code, notes, and snippets.

@kungfumike
Created October 24, 2013 16:51
Show Gist options
  • Save kungfumike/7140877 to your computer and use it in GitHub Desktop.
Save kungfumike/7140877 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'celluloid'
find_val = ARGV[0].to_i
selection_vector = ARGV[1].split(',').map(&:to_i).sort
if selection_vector.length == 1
selection_vector = selection_vector[0].times.collect{|i| rand(10)}
end
puts "Searching for sub sets that sum to #{find_val} within #{selection_vector.inspect}"
#puts selection_vector.methods.sort.inspect
#selection_vector.permutation.each {|p| puts p.inspect}
module SubsetSum
attr_reader :selection_vector
attr_reader :solve_for
def initialize(selection_vector, solve_for)
@selection_vector = selection_vector
@solve_for = solve_for
end
end
class SsCelluloid
include Celluloid
include SubsetSum
def solve_threaded
1.upto(selection_vector.length).to_a.collect do |n|
solver = SsCelluloid.new(selection_vector, solve_for)
solutions = solver.future :solutions_for_permutations_of_length, n
solutions.value
end.to_a.reject(&:empty?)
end
def solutions_for_permutations_of_length ourlen
res = []
res.push(selection_vector.combination(ourlen).select do |a|
(a.inject(0) {|sum,e| sum = sum + e }) == solve_for
end)
res.reject(&:empty?)
end
end
start = Time.now
ss = SsCelluloid.new(selection_vector, find_val)
puts ss.solve_threaded.inspect
puts "Elapsed time: #{Time.now - start}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment