jeanwei
6/21/2016 - 3:22 AM

sample.unsolved.txt

005030081902850060600004050007402830349760005008300490150087002090000600026049503
609238745204561098853947021486352179702614583031879264945723806328196457167085932
105802000090076405200400819019007306762083090000061050007600030430020501600308900
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