Class | ConstraintSolver::AllDifferentConstraint |
In: |
lib/AllDifferentConstraint.rb
|
Parent: | AbstractConstraint |
Represents the all different constraint.
variables | [R] |
Initialises a new all different constraint. The constructor takes the list of variables that must be different as an argument.
# File lib/AllDifferentConstraint.rb, line 13 def initialize(variables) if variables.empty? or variables.size == 1 raise ArgumentError, "List of variables must contain at least two elements!" end @variables = variables end
# File lib/AllDifferentConstraint.rb, line 54 def ==(constraint) return false unless constraint.kind_of?(AllDifferentConstraint) @variables == constraint.variables end
# File lib/AllDifferentConstraint.rb, line 38 def allAssigned? (@variables.collect { |var| var.assigned? }).foldLeft(Proc.new { |a,b| a & b }) end
Checks whether all the variables have different values assigned to them.
# File lib/AllDifferentConstraint.rb, line 22 def holds? if allAssigned? @variables.each { |variable| @variables.eachAfter(variable) { |otherVariable| if variable.value == otherVariable.value return false end } } else raise RuntimeError, "Cannot check whether " + self.to_s + " holds because not all variables have been assigned values!" end return true end
# File lib/AllDifferentConstraint.rb, line 42 def include?(variable) @variables.include?(variable) end
# File lib/AllDifferentConstraint.rb, line 65 def revise revisedVariables = Array.new pruneList = Set.new @variables.find_all { |var| var.assigned? }.each { |assigned| pruneList << assigned.value } unassignedVariables = @variables.find_all { |var| not var.assigned? } unassignedVariables.each { |unassigned| unless (unassigned.domain.values & pruneList).empty? unassigned.domain.prune(pruneList) revisedVariables << unassigned end } if unassignedVariables.size > ((unassignedVariables.collect { |var| var.values }).foldLeft(Proc.new { |x,y| x | y })).size revisedVariables.each { |var| var.domain.undoPruning } raise DomainWipeoutException end return revisedVariables, 0 end
# File lib/AllDifferentConstraint.rb, line 46 def to_s @variables.collect { |var| var.name }.join(" != ") end