目前我的代码如下:
def sudoku_generator
@initial_board = [0] * 81
a = (1..9).sort_by{rand}
b = (1..9).sort_by{rand}
c = (1..9).sort_by{rand}
@initial_board[0..2] = a[0..2]
@initial_board[9..11] = a[3..5]
@initial_board[18..20] = a[6..8]
@initial_board[30..32] = b[0..2]
@initial_board[39..41] = b[3..5]
@initial_board[48..50] = b[6..8]
@initial_board[60..62] = c[0..2]
@initial_board[69..71] = c[3..5]
@initial_board[78..80] = c[6..8]
@initial_board.each_slice(9) do |make_better|
puts make_better.join(' | ')
end
end
print sudoku_generator
返回:
3 | 7 | 9 | 0 | 0 | 0 | 0 | 0 | 0
1 | 5 | 6 | 0 | 0 | 0 | 0 | 0 | 0
2 | 8 | 4 | 0 | 0 | 0 | 0 | 0 | 0
0 | 0 | 0 | 1 | 5 | 8 | 0 | 0 | 0
0 | 0 | 0 | 6 | 7 | 2 | 0 | 0 | 0
0 | 0 | 0 | 3 | 4 | 9 | 0 | 0 | 0
0 | 0 | 0 | 0 | 0 | 0 | 5 | 1 | 3
0 | 0 | 0 | 0 | 0 | 0 | 4 | 8 | 7
0 | 0 | 0 | 0 | 0 | 0 | 6 | 2 | 9
我正在尝试找到一种方法,现在用下划线“_”替换此数组中的零。对于任何反馈,我们都表示感谢。感谢。
答案 0 :(得分:2)
正如@sawa在评论中建议的那样,我将数组默认为'_'
,但您可以在打印时始终0
替换'_'
:
puts make_better.map { |x| x == 0 ? '_' : x }.join(' | ')
答案 1 :(得分:1)
如何使用课程?它是一种面向对象的语言,对吧?我想方法#to_s
本来可以更漂亮。
class Grid
SIZE = 3
def initialize
@array = Array.new(3) { |line| Array.new(3) { |column| generator.call(line, column) } }
end
def generator
proc { '_' }
end
def to_a
@array
end
end
class RandomGrid < Grid
def generator
@random_numbers ||= (1..9).to_a.shuffle
proc { @random_numbers.shift }
end
end
class DiagonalBoard < Grid
def generator
proc { |line, column| (line == column ? RandomGrid : Grid).new }
end
def to_s
@array.map do |grids|
grids.map(&:to_a).transpose.map do |rows|
rows.flatten.join('|')
end.join("\n")
end.join("\n")
end
end
puts DiagonalBoard.new
输出
9|2|8|_|_|_|_|_|_
5|3|7|_|_|_|_|_|_
1|4|6|_|_|_|_|_|_
_|_|_|8|1|5|_|_|_
_|_|_|6|2|9|_|_|_
_|_|_|3|4|7|_|_|_
_|_|_|_|_|_|2|9|1
_|_|_|_|_|_|7|5|6
_|_|_|_|_|_|3|8|4