Sha256: 9ef2b12d7fc18e7a6aaef1fa9d9c09eafa6c8db11e25a6cafbf8c9650189319d

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

#!/usr/bin/ruby

require 'set'

module ConstraintSolver
    # This class represents the domain of a variable, i.e. a set of values that
    # can be assigned to the variable.
    class Domain
	attr_reader :values, :undoStack
	# Initialises a new domain. Optionally, a set of initial values can be
	# given.
	def initialize(values=nil)
	    if not (values.nil? or values.kind_of?(Set))
		raise ArgumentError, "Values must be a set!"
	    end
	    @values = values.nil? ? Set.new : values
	    @undoStack = Array.new
	end

	# Adds value to the domain.
	def <<(value)
	    @values << value
	end

	# Deletes value from the domain.
	def delete(value)
	    @values.delete(value)
	end

	def size
	    @values.size
	end

	def first
	    @values.entries[0]
	end

	def include_any?(enum)
	    @values.include_any?(enum)
	end

	def each
	    @values.each { |value|
		yield value
	    }
	end

	def sort(&block)
	    @values.sort(&block)
	end

	def collect(&block)
	    values.collect(&block)
	end

	def empty?
	    @values.empty?
	end

	# Prunes the values from the domain.
	def prune(values)
	    if not values.kind_of?(Set)
		values = Set.new([ values ])
	    end
	    @undoStack.push(@values)
	    @values -= values
	    if @values.empty?
		raise DomainWipeoutException
	    end
	end

	# Undoes pruning by replacing the current list of values with the one
	# before the last time prune was called.
	def undoPruning
	    if @undoStack.empty?
		raise UndoStackEmptyException, "No more prunes to undo!"
	    end
	    @values = @undoStack.pop
	end

	def include?(value)
	    @values.include?(value)
	end

	def to_s
	    "{" + @values.entries.join(", ") + "}"
	end

	def ==(domain)
	    return false unless domain.kind_of?(Domain)
	    (@values == domain.values) and (@undoStack == domain.undoStack)
	end
    end

    class UndoStackEmptyException < Exception
    end

    class DomainWipeoutException < Exception
    end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ConstraintSolver-0.1 lib/Domain.rb