example/sudoku-set.rb in gecoder-0.8.3 vs example/sudoku-set.rb in gecoder-0.9.0
- old
+ new
@@ -21,17 +21,17 @@
# given numbers from 1 to 81. Each set therefore has an empty lower bound
# (since we have no guarantees where a number will end up) and 1..81 as
# upper bound (as it may potentially occurr in any square). We know that
# each assignable number must occurr 9 times in a solved sudoku, so we
# set the cardinality to 9..9 .
- @sets = set_var_array(n, [], 1..n*n, n..n)
+ sets_is_an set_var_array(n, [], 1..n*n, n..n)
predefined_values.row_size.times do |i|
predefined_values.column_size.times do |j|
unless predefined_values[i,j].zero?
# We add the constraint that the square position must occurr in the
# set corresponding to the predefined value.
- @sets[predefined_values[i,j] - 1].must_be.superset_of [i*n + j+1]
+ sets[predefined_values[i,j] - 1].must_be.superset_of [i*n + j+1]
end
end
end
# Build arrays containing the square positions of each row and column.
@@ -56,38 +56,37 @@
# All sets must be pairwise disjoint since two numbers can't be assigned to
# the same square.
n.times do |i|
(i + 1).upto(n - 1) do |j|
- @sets[i].must_be.disjoint_with @sets[j]
+ sets[i].must_be.disjoint_with sets[j]
end
end
# The sets must intersect in exactly one element with each row column and
# block. I.e. an assignable number must be assigned exactly once in each
- # row, column and block. We specify the constraint by expressing that the
- # intersection must be equal with a set variable with cardinality 1.
- @sets.each do |set|
+ # row, column and block.
+ sets.each do |set|
rows.each do |row|
- set.intersection(row).must == set_var([], 1..n*n, 1..1)
+ set.intersection(row).size.must == 1
end
columns.each do |column|
- set.intersection(column).must == set_var([], 1..n*n, 1..1)
+ set.intersection(column).size.must == 1
end
blocks.each do |block|
- set.intersection(block).must == set_var([], 1..n*n, 1..1)
+ set.intersection(block).size.must == 1
end
end
# Branching.
- branch_on @sets, :variable => :none, :value => :min
+ branch_on sets, :variable => :none, :value => :min
end
# Outputs the assigned numbers in a grid.
def to_s
squares = []
- @sets.values.each_with_index do |positions, i|
+ sets.values.each_with_index do |positions, i|
positions.each{ |square_position| squares[square_position - 1] = i + 1 }
end
squares.enum_slice(@size).map{ |slice| slice.join(' ') }.join("\n")
end
end
@@ -102,6 +101,6 @@
[6,0,9, 0,0,0, 0,0,1],
[0,8,0, 4,0,0, 1,0,0],
[0,6,3, 0,0,0, 0,8,0],
[0,0,0, 6,0,8, 0,0,0]]
-puts(SudokuSet.new(predefined_squares).solve! || 'Failed').to_s
\ No newline at end of file
+puts SudokuSet.new(predefined_squares).solve!.to_s