Created
June 26, 2012 16:53
-
-
Save jessieay/2997095 to your computer and use it in GitHub Desktop.
Sudoku solver with everything but final solve method working
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Board | |
def initialize(board_input) | |
@board_array = [] | |
board_input.split(//).each_with_index do |cell, index| | |
@board_array << Cell.new(cell, index) | |
end | |
end | |
def find_box(cell_id) | |
((cell_id % 9) / 3) + ((cell_id / 27) * 3) | |
end | |
def box_fill(cell_id) | |
@current_box = [] | |
@box_id = find_box(cell_id) | |
@board_array.select do |cell| | |
if find_box(cell.id) == @box_id | |
@current_box << cell.value | |
end | |
end | |
@current_box | |
end | |
def find_row(cell_id) | |
cell_id / 9 | |
end | |
def row_fill(cell_id) | |
@current_row = [] | |
@row_id = find_row(cell_id) | |
@board_array.select do |cell| | |
if find_row(cell.id) == @row_id | |
@current_row << cell.value | |
end | |
end | |
@current_row | |
end | |
def find_column(cell_id) | |
cell_id % 9 | |
end | |
def column_fill(cell_id) | |
@current_column = [] | |
@column_id = find_column(cell_id) | |
@board_array.select do |cell| | |
if find_column(cell.id) == @column_id | |
@current_column << cell.value | |
end | |
end | |
@current_column | |
end | |
def solve | |
current = @board_array.each do |cell| | |
cell.value | |
end | |
if current.include? 0 | |
@board_array.each do |cell| | |
if cell.value == 0 | |
neighbors = (box_fill(cell.id) | column_fill(cell.id) | | |
row_fill(cell.id)) | |
all = [1,2,3,4,5,6,7,8,9] | |
options = all - neighbors | |
if options.length == 1 | |
cell.update(options[0]) | |
end | |
end | |
end | |
# else | |
# puts @board_array.each do |cell| | |
# cell.value | |
# end | |
end | |
end | |
end | |
class Cell | |
attr_accessor :value, :id | |
def initialize(value, id) | |
@value = value | |
@id = id | |
end | |
def update(new_value) | |
@value = new_value | |
end | |
end | |
board = Board.new("619030040270061008000047621486302079000014580031009060005720806320106057160400030") | |
board.solve |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment