class Sudoku::Solver
This class provides method for solving or checking solution of the Sudoku
game.
Public Class Methods
Will initialize this solver with given grid. Exception is thrown if the given grid is not kind of Sudoku::Grid
# File lib/sudoku/solver.rb, line 9 def initialize(grid) fail ArgumentError, 'Invalid grid passed to solver' unless grid.is_a?(Grid) @grid = grid end
Public Instance Methods
Will return true, if in some area of the grid are duplicit or illegal numbers. Returns false otherwise.
# File lib/sudoku/solver.rb, line 53 def areas_violated? [(0..2), (3..5), (6..8)].repeated_permutation(2).each do |x, y| cells = @grid.cells.select { |cell| cell.in_area(x, y) } return true if cells_violated?(cells) end false end
Will return true, if given set of cells does not contain duplicities in values other than 0.
-
cells
set of cells to check.
# File lib/sudoku/solver.rb, line 46 def cells_violated?(cells) values = cells.select { |x| x.value != 0 }.collect(&:value) values.uniq.size != values.size end
Will return true, if all cols are correctly solved.
# File lib/sudoku/solver.rb, line 39 def cols_violated? (0..8).to_a.collect { |x|cells_violated?(@grid.get_col(x)) }.any? end
Will return true, if the grid is filled, which means, that all of the values are other than 0. False otherwise.
# File lib/sudoku/solver.rb, line 29 def grid_filled? @grid.filled? end
Will return true, if all rows are correctly solved.
# File lib/sudoku/solver.rb, line 34 def rows_violated? (0..8).to_a.collect { |x|cells_violated?(@grid.get_row(x)) }.any? end
Will check if the sudoku rules are violated, but the 0 value is ignored. Returns true if violated, false otherwise.
# File lib/sudoku/solver.rb, line 17 def rules_violated? rows_violated? || cols_violated? || areas_violated? end
Will return true, if all cells of the grid are filled and no Sudoku
rule is violated.
# File lib/sudoku/solver.rb, line 23 def solved? !rules_violated? && grid_filled? end