[SOLUTION] Constraint Processing (#70)

D

David Tran

Just finish my solution, I run out of time to provide an example ...
define the domain as instance variable.
define the rule by using block & instance variable.
define the solution block by using instance variable.
( all block will exec on "Engine"'s instance_eval )


class Engine

def go(&solution)
solve(instance_variables, &solution)
end

private
def method_missing(name, *args, &block)
if name.to_s =3D~ /=3D$/ && block.nil?
vars(name, *args)
elsif args.size =3D=3D 0 && !block.nil?
rules(name, &block)
else
super
end
end

def rules(name, &block)
self.class.send:)define_method, name, &block)
self.class.send:)protected, name)
end

def vars(name, *args)
name =3D name.to_s.sub(/=3D$/, '')
self.class.class_eval("attr_accessor :#{name}")
args =3D args[0] if args.size =3D=3D 1 && args[0].respond_to?:)each)
instance_variable_set("@#{name}", args)
end

def solve(vars, &solution)
if (vars.size !=3D 0)
name =3D vars.shift
value =3D instance_variable_get(name)
value.each { |e|
instance_variable_set(name, e)
solve(vars.dup, &solution)
}
instance_variable_set(name, value)
else
protected_methods.each { |method|
return if !send(method)
}
instance_eval(&solution)
end
end

end

if __FILE__ =3D=3D $0
e =3D Engine.new
e.a =3D 0..4
e.b =3D 0..4
e.c =3D 0..4
e.rule1 { @a < @b }
e.rule2 { @a + @b =3D=3D @c }
e.go { puts "a =3D> #@a, b =3D> #@b, c =3D> #@c" }
end


__END__
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top