-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudoku.rb
56 lines (46 loc) · 890 Bytes
/
sudoku.rb
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
class Sudoku
attr_reader :matrix
BLANK = '.'
def initialize(matrix)
@matrix = matrix
end
def row(x)
matrix[x]
end
def column(y)
matrix.map { |row| row[y] }
end
def at((x,y))
matrix[y][x]
end
def empty?(cell)
at(cell) == BLANK
end
def write(n, (x, y))
matrix[y][x] = n
end
def erase(cell)
write(BLANK, cell)
end
def subgrid_neighbors(x,y)
base_x = x - (x % 3)
base_y = y - (y % 3)
matrix[base_y,3].flat_map { |row| row[base_x, 3] }
end
def unknowns
indexes = (0..8).to_a
indexes.product(indexes)
.select { |cell| empty? cell }
end
def to_s
matrix.each_slice(3).map do |rows|
rows.map do |row|
row.each_slice(3)
.map { |group| group.join(' ') }
.join('|')
end
.join("\n")
end
.join("\n-----+-----+-----\n")
end
end