Skip to content

Instantly share code, notes, and snippets.

@jackcallister
Created April 14, 2020 08:36
Show Gist options
  • Save jackcallister/577756cc9a6ec172fe27b91cedd9009a to your computer and use it in GitHub Desktop.
Save jackcallister/577756cc9a6ec172fe27b91cedd9009a to your computer and use it in GitHub Desktop.
BOX_MAP = [
[0, 1, 2, 9, 10, 11, 18, 19, 20],
[3, 4, 5, 12, 13, 14, 21, 22, 23],
[6, 7, 8, 15, 16, 17, 24, 25, 26],
[27, 28, 29, 36, 37, 38, 45, 46, 47],
[30, 31, 32, 39, 40, 41, 48, 49, 50],
[33, 34, 35, 42, 43, 44, 51, 52, 53],
[54, 55, 56, 63, 64, 65, 72, 73, 74],
[57, 58, 59, 66, 67, 68, 75, 76, 77],
[60, 61, 62, 69, 70, 71, 78, 79, 80],
]
ROW_MAP = [
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[9, 10, 11, 12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44],
[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80]
]
COLUMN_MAP = [
[0, 9, 18, 27, 36, 45, 54, 63, 72],
[1, 10, 19, 28, 37, 46, 55, 64, 73],
[2, 11, 20, 29, 38, 47, 56, 65, 74],
[3, 12, 21, 30, 39, 48, 57, 66, 75],
[4, 13, 22, 31, 40, 49, 58, 67, 76],
[5, 14, 23, 32, 41, 50, 59, 68, 77],
[6, 15, 24, 33, 42, 51, 60, 69, 78],
[7, 16, 25, 34, 43, 52, 61, 70, 79],
[8, 17, 26, 35, 44, 53, 62, 71, 80]
]
def box_index(cell)
BOX_MAP.each_with_index do |b, i|
return i if b.include? cell
end
end
def row_index(cell)
ROW_MAP.each_with_index do |b, i|
return i if b.include? cell
end
end
def column_index(cell)
COLUMN_MAP.each_with_index do |b, i|
return i if b.include? cell
end
end
def box_numbers(sudoku, cell)
BOX_MAP[box_index(cell)].map { |i| sudoku[i] }
end
def row_numbers(sudoku, cell)
ROW_MAP[row_index(cell)].map { |i| sudoku[i] }
end
def column_numbers(sudoku, cell)
COLUMN_MAP[column_index(cell)].map { |i| sudoku[i] }
end
def print_solution(solution)
solution.each_slice(9).to_a.each { |r| puts r.join(", ") }
end
def intersecting_numbers(sudoku, cell)
box_numbers(sudoku, cell) + row_numbers(sudoku, cell) + column_numbers(sudoku, cell)
end
def cell_location_is_valid?(sudoku, cell, number)
!intersecting_numbers(sudoku, cell).include? number
end
def find_empty_cell(sudoku)
sudoku.find_index(0)
end
def solve(sudoku)
cell = find_empty_cell(sudoku)
return sudoku if !cell
for number in [*1..9] do
if cell_location_is_valid?(sudoku, cell, number)
sudoku[cell] = number
return sudoku if solve(sudoku)
sudoku[cell] = 0
end
end
return false
end
sudoku = [
0, 1, 6, 0, 3, 0, 0, 0, 0,
0, 0, 9, 0, 0, 7, 0, 0, 0,
0, 8, 0, 9, 5, 0, 3, 0, 0,
0, 7, 0, 0, 0, 0, 9, 0, 0,
0, 9, 0, 5, 0, 2, 0, 6, 0,
0, 0, 1, 0, 0, 0, 0, 8, 0,
0, 0, 7, 0, 6, 4, 0, 9, 0,
0, 0, 0, 2, 0, 0, 7, 0, 0,
0, 0, 0, 0, 7, 0, 1, 3, 0,
]
print_solution(solve(sudoku))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment