Sha256: ed1e9cc373fa464300ddc31c8ad1f0bcb2002635e2e0da5356d13f4777d8350f
Contents?: true
Size: 1.55 KB
Versions: 1
Compression:
Stored size: 1.55 KB
Contents
#!/usr/bin/ruby module ConstraintSolver # This class represents a solution to a constraint satisfaction problem. class Solution attr_reader :variables, :merit, :violation # Initialises a new solution with a list of variables. The variables # must all have values assigned to them. # Optionally, a map to map domain values of variables to their merit and # a number designating the cost of violating constraints in the solution can # be specified. def initialize(variables, meritMap={}, violation=0) if not variables.kind_of?(Array) variables = Array.new([ variables ]) end if variables.inject(true) { |res,var| res & var.assigned? } @variables = Array.new variables.each { |variable| @variables << variable.dup } else raise ArgumentError, "All variables must have values assigned to them!" end @merit = 0 @variables.each { |var| @merit += meritMap[var.value] ? var.merit * meritMap[var.value] : var.merit } @violation = violation @merit -= @violation end def each @variables.each { |variable| yield variable } end def <=>(solution) @value <=> solution.value end def ==(solution) return false unless solution.kind_of?(Solution) @variables == solution.variables and @merit == solution.merit and @violation == solution.violation end def to_s s = (@variables.collect { |variable| variable.to_s }).join(", ") s += ", merit " + @merit.to_s unless @merit.nil? s += ", violation " + @violation.to_s unless @violation.nil? return s end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
ConstraintSolver-0.1 | lib/Solution.rb |