Class: CombinatorialPuzzleSolver::Constraint

Inherits:
Array
  • Object
show all
Defined in:
lib/combinatorial_puzzle_solver/constraint.rb

Overview

A collection of identifiers that all should have unique values, like a row or a column in a Sudoku puzzle.

Specifications

is an array

Instance Method Summary (collapse)

Constructor Details

- (Constraint) initialize(identifiers)

Returns a new instance of Constraint



8
9
10
11
12
13
14
# File 'lib/combinatorial_puzzle_solver/constraint.rb', line 8

def initialize(identifiers)
  super(identifiers)
  fail unless identifiers.is_a?(Array)
  identifiers.each{|id| fail unless id.is_a?(Identifier)}

  each{|identifier| identifier.constraints << self }
end

Instance Method Details

- (Hash<Object,Set<Identifier>>) possible_values(solution_space)

Returns a map between each possible value within this constraint and the set of identifiers that can have them.

Parameters:

  • solution_space (SolutionSpace)

    the mapping between the puzzle's identifiers and the values they can have.

Returns:

  • (Hash<Object,Set<Identifier>>)

    a map between each possible value within this constraint and the set of identifiers that can have them.

Specifications:

should return a Hash

should contain each value, and the identifiers that can have them.



43
44
45
46
47
48
49
50
51
52
# File 'lib/combinatorial_puzzle_solver/constraint.rb', line 43

def possible_values(solution_space)
  values = Hash.new{|value,ids| value[ids] = Set.new }

  each{|identifier|
    solution_space[identifier].each{|value|
      values[value] << identifier
    }
  }
  values
end

- (Hash<Identifier,Object>) resolvable_identifiers(solution_space, resolvable = Hash.new)

Iterates all possible values that can be set within this constraint, and when a value can only be placed within that specific identifier.

Parameters:

  • solution_space (SolutionSpace)

    the mapping between the puzzle's identifiers and the values they can have.

  • resolvable (Hash<Identifier,Object>) (defaults to: Hash.new)

    an optional Hash to store all identifiers and values that becomes resolvable.

Returns:

  • (Hash<Identifier,Object>)

    the identifiers that can be resolved, mapped to the only value they can have.

Specifications:

should return a Hash

should return the identifiers mapped to their resolved value



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/combinatorial_puzzle_solver/constraint.rb', line 26

def resolvable_identifiers(solution_space, resolvable=Hash.new)
  possible_values(solution_space).each{|value, identifiers|
    if identifiers.size == 1 then
      resolved_identifier = identifiers.first
      unless solution_space[resolved_identifier].resolved? then
        resolvable[resolved_identifier] = value
      end
    end
  }
  resolvable
end