Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module RubySudoku
- class Solver
- def initialize(input)
- end
- def solution
- end
- end
- class Game
- def initialize(input)
- @input = input
- end
- def cell(x)
- @input[x]
- end
- def cell_at(col_idx, row_idx)
- cell(cell_index(col_idx, row_idx))
- end
- def row_at(cell_idx)
- cell_idx / 9
- end
- def column_at(cell_idx)
- cell_idx % 9
- end
- def box_at(cell_idx)
- row = row_at(cell_idx)
- col = column_at(cell_idx)
- (row/3)*3 + (col/3)
- end
- def row(row_number)
- row_indices(row_number).collect { |idx| cell(idx) }
- end
- def column(column_number)
- column_indices(column_number).collect { |idx| cell(idx) }
- end
- def box(box_number)
- box_indices(box_number).collect { |idx| cell(idx) }
- end
- def possible_values(cell_idx)
- row_num = row_at(cell_idx)
- col_num = column_at(cell_idx)
- box_num = box_at(cell_idx)
- row_vals = row(row_num)
- col_vals = column(col_num)
- box_vals = box(box_num)
- (1..9).to_a - row_vals - col_vals - box_vals
- end
- def fill_constrained_cells
- cell_idxs = (0..80).collect do |cell_idx|
- poss = possible_values(cell_idx)
- if cell(cell_idx) == 0 && poss.size == 1
- puts poss
- set_cell(cell_idx, poss)
- cell_idx
- end
- end
- cell_idxs.compact
- end
- def solve_attempt
- cons_cells = fill_constrained_cells
- while cons_cells.size > 0
- cons_cells = fill_constrained_cells
- end
- if not solved?
- puts 'Failed the puzzle'
- end
- end
- def solved?
- @input.each do |cell|
- if cell == 0
- return false
- end
- end
- return true
- end
- protected
- def set_cell(x, y)
- @input[x] = y
- end
- def column_indices(column_number)
- (0..8).collect { |x| x * 9 + column_number }
- end
- def cell_index(col_idx, row_idx)
- cell_index = row_idx * 9 + col_idx
- end
- def row_indices(row_number)
- start_idx = row_number * 9
- end_idx = start_idx + 8
- (start_idx..end_idx).to_a
- end
- def box_indices(box_number)
- start_row = (box_number / 3) * 3
- start_col = (box_number % 3) * 3
- indices = []
- (start_row..start_row + 2).each do |row_idx|
- (start_col..start_col + 2).each do |col_idx|
- indices << cell_index(col_idx, row_idx)
- end
- end
- indices
- end
- end
- end
Add Comment
Please, Sign In to add comment