Sha256: 211e0eed27b61e9bc6b3a0ef7de4dcc691dcafff2f26c46d2af3876d9f957965

Contents?: true

Size: 1.85 KB

Versions: 1

Compression:

Stored size: 1.85 KB

Contents

#!/usr/bin/ruby

module ConstraintSolver
    # This class represents a variable in a constraint satisfaction problem.
    class Variable
	attr_reader :name, :domain, :value, :merit
	# Initialises a new variable. The name of the variable and at least one
	# of domain or value are required.
	# If domain is nil and a value is given, a new Domain is constructed
	# with only the value specified in it.
	# The fourth argument is the merit of the variable.
	def initialize(name, domain=nil, value=nil, merit=0)
	    if not name.kind_of?(String)
		raise ArgumentError, "The name of the variable has to be specified."
	    end
	    if domain.nil? and value.nil?
		raise ArgumentError, "At least one of domain or value are required."
	    end
	    @name = name
	    @value = value
	    if not domain.nil? and not domain.kind_of?(Domain)
		domain = Domain.new([ domain ].to_set);
	    end
	    if value.nil?
		@domain = domain.nil? ? Domain.new : domain
	    else
		if domain.nil?
		    @domain = Domain.new([ value ].to_set)
		else
		    if domain.include?(value)
			@domain = domain
		    else
			raise ArgumentError, "Value " + value.to_s + " not in domain " + domain.to_s + "!"
		    end
		end
	    end
	    @merit = merit
	end

	# Assigns a new value to the variable.
	# The new value has to be in the domain of the variable.
	def value=(value)
	    if value.nil?
		return
	    end
	    if @domain.include?(value)
		@value = value
	    else
		raise ArgumentError, "The domain of " + @name.to_s + " (" + @domain.to_s +
		    ") does not contain " + value.to_s + "!"
	    end
	end

	def values
	    domain.values
	end

	def to_s
	    @name.to_s + " = " + @value.to_s + " \\in " + @domain.to_s
	end

	def ==(variable)
	    variable.kind_of?(Variable) and (@name == variable.name) and (@value == variable.value)
	end

	def assigned?
	    not @value.nil?
	end

	def reset
	    @value = nil
	end
    end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ConstraintSolver-0.1 lib/Variable.rb