Class: ConstraintSolver::Solution

Inherits:
Object
  • Object
show all
Defined in:
lib/Solution.rb

Overview

This class represents a solution to a constraint satisfaction problem.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(variables, meritMap = {}, violation = 0) ⇒ Solution

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.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/Solution.rb', line 12

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

Instance Attribute Details

#meritObject (readonly)

Returns the value of attribute merit.



6
7
8
# File 'lib/Solution.rb', line 6

def merit
  @merit
end

#variablesObject (readonly)

Returns the value of attribute variables.



6
7
8
# File 'lib/Solution.rb', line 6

def variables
  @variables
end

#violationObject (readonly)

Returns the value of attribute violation.



6
7
8
# File 'lib/Solution.rb', line 6

def violation
  @violation
end

Instance Method Details

#<=>(solution) ⇒ Object



38
39
40
# File 'lib/Solution.rb', line 38

def <=>(solution)
    @value <=> solution.value
end

#==(solution) ⇒ Object



42
43
44
45
# File 'lib/Solution.rb', line 42

def ==(solution)
    return false unless solution.kind_of?(Solution)
    @variables == solution.variables and @merit == solution.merit and @violation == solution.violation
end

#eachObject



32
33
34
35
36
# File 'lib/Solution.rb', line 32

def each
    @variables.each { |variable|
	yield variable
    }
end

#to_sObject



47
48
49
50
51
52
53
54
# File 'lib/Solution.rb', line 47

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