class Sudoku
def initialize(board_string)
@row_string = String.new(board_string).split('')
@row = Array.new(9){@row_string.shift(9)}
@column = @row.transpose
end
def solve!
# check if sudoku board contains any zeros
# find method for checking array for a target elemnt
while @row.flatten.include?("0")
@row.each_with_index do |row, r_ind|
row.each_with_index do |num, c_ind|
if num == "0"
solution = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
has_num = get_column(c_ind) + get_row(r_ind) + get_grid(r_ind, c_ind)
possibility = solution - has_num.uniq!
if possibility.size == 1
@column[c_ind][r_ind] = possibility[0]
@row[r_ind][c_ind] = possibility[0]
end
end
end
end
end
end
def get_column(index)
@column[index]
end
def get_row(index)
@row[index]
end
def get_grid(x, y)
matrixID = [0, 0, 0, 3, 3, 3, 6, 6, 6]
grid = []
3.times do |xtime|
3.times do |ytime|
grid << @row[matrixID[x] + xtime][matrixID[y] + ytime]
end
end
grid
end
# Returns a string representing the current state of the board
# Don't spend too much time on this method; flag someone from staff
# if you are.
def board
@row.each_with_index do |row, rindex|
if rindex % 3 == 0
print "\n---------------------"
end
row.each_with_index do |num, cindex|
if cindex % 3 == 0 && cindex != 0
print "| "
end
if cindex % 9 != 0
print "#{num} "
else
print "\n#{num} "
end
end
end
print "\n---------------------\n"
end
end
# The file has newlines at the end of each line, so we call
# String#chomp to remove them.
board_string = File.readlines('sample.unsolved.txt').first.chomp
game = Sudoku.new(board_string)
game.board
# Remember: this will just fill out what it can and not "guess"
game.solve!
game.board