Skip to content

Instantly share code, notes, and snippets.

@aarti
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save aarti/70c1cce6921aab4fcd43 to your computer and use it in GitHub Desktop.

Select an option

Save aarti/70c1cce6921aab4fcd43 to your computer and use it in GitHub Desktop.
class SudokuSolver
attr_accessor :grid
def initialize
@grid = Array.new(9) { Array.new(9) }
end
def initial_values(vals)
vals.each do |v|
x,y,val = v[0],v[1],v[3]
@grid[x][y] = val
end
end
def to_s
@grid.each do |rows|
rows.each do |cols|
print "#{cols} " if cols
print "X " unless cols
end
puts ''
end
end
def in_row(i,k)
@grid[i].include? k
end
def in_col(j,k)
0.upto(8) do |i|
# p self.to_s
return true if @grid[i][j] == k
end
false
end
def in_grid(i,j,k)
x,y =0,0
x = 3 if i > 2
x = 6 if i > 5
y = 3 if j > 2
y = 6 if j > 5
x.upto(x+2) do |xx|
y.upto(y+2) do |yy|
return true if @grid[xx][yy] == k
end
end
return false
end
def find_unassigned_location
@grid.each_with_index do |rows,i|
rows.each_with_index do |cols,j|
return [i,j] unless cols
end
end
false
end
def solve
# If there is no unassigned location, we are done
cell = find_unassigned_location
return true unless cell # No unassigned cell remaining
i,j = cell[0],cell[1]
1.upto(9) do |k|
next if in_row(i,k) || in_col(j,k) || in_grid(i,j,k)
@grid[i][j] = k
return true if solve # Recursively solve
@grid[i][j] = nil # Unassign location if recursive solution returns false
end
return false
end
end
s = SudokuSolver.new
# [x,y,value_in_grid]
initial_vals =[[0,1,2],[1,5,3],[6,1,4],[7,3,5],[8,6,8],[4,4,9]]
s.initial_values(initial_vals)
s.solve
s.to_s
## Ouput
# 1 2 3 4 5 6 7 8 9
# 4 5 7 9 8 3 1 2 6
# 6 8 9 1 2 7 3 4 5
# 2 1 4 3 6 5 9 7 8
# 3 6 5 7 9 8 2 1 4
# 7 9 8 2 1 4 5 6 3
# 5 4 1 8 7 9 6 3 2
# 8 7 6 5 3 2 4 9 1
# 9 3 2 6 4 1 8 5 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment