📄 javaamb.txt
字号:
class Sudoku
def initialize
@square = Array.new(9) { Array.new(9) {0} }
@amb = Amb.new
end
def find_sudoku
9.times do |row|
9.times do |col|
candidate = @amb.choose(*range)
@square[row][col] = 0
@amb.assert(count_in_row(row, candidate) == 0)
@amb.assert(count_in_col(col, candidate) == 0)
@amb.assert(count_in_sub_square(row, col, candidate) == 0)
@square[row][col] = candidate
end
end
end
def range
result,range = [], [1,2,3,4,5,6,7,8,9]
9.times do
result << range[index = rand(range.size)]
range.delete_at index
end
result
end
def count_in_row row, candidate
@square[row].inject(0) {|count, num| (num == candidate) ? count + 1 : count}
end
def count_in_col col, candidate
@square.inject(0) {|count, row| (row[col] == candidate) ? count + 1 : count}
end
def count_in_sub_square row, col, candidate
start_row, start_col = row / 3, col / 3
count = 0
3.times {|i| 3.times {|j| count += 1 if @square[start_row * 3 + i][start_col * 3 + j] == candidate}}
count
end
def create_sudoku number
find_sudoku
number.times { @square[rand(9)][rand(9)] = 0}
end
def next
begin
@amb.failure
create_sudoku
rescue Amb::ExhaustedError
raise 'no more Sudoku'
end
end
def inspect
result = ""
9.times do |row|
9.times {|col| result << (@square[row][col] == 0 ? '?' : @square[row][col].to_s) << ' '}
result << "\n"
end
result
end
end
sudoku = Sudoku.new
sudoku.create_sudoku 30
p sudoku
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -