-
Notifications
You must be signed in to change notification settings - Fork 0
/
board.rb
85 lines (68 loc) · 1.33 KB
/
board.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
require_relative "tile"
class Board
def self.empty_grid
Array.new(9) do
Array.new(9) { Tile.new(0) }
end
end
def self.from_file(filename)
rows = File.readlines(filename).map(&:chomp)
tiles = rows.map do |row|
nums = row.split("").map { |char| Integer(char) }
nums.map { |num| Tile.new(num) }
end
self.new(tiles)
end
def initialize(grid = self.empty_grid)
@grid = grid
end
def [](pos)
x, y = pos
grid[x][y]
end
def []=(pos, value)
x, y = pos
tile = grid[x][y]
tile.value = value
end
def columns
rows.transpose
end
def render
puts " #{(0..8).to_a.join(" ")}"
grid.each_with_index do |row, i|
puts "#{i} #{row.join(" ")}"
end
end
def rows
grid
end
def size
grid.size
end
def solved?
rows.all? { |row| solved_set?(row) } &&
columns.all? { |col| solved_set?(col) } &&
squares.all? { |square| solved_set?(square) }
end
def solved_set?(tiles)
nums = tiles.map(&:value)
nums.sort == (1..9).to_a
end
def square(idx)
tiles = []
x = (idx / 3) * 3
y = (idx % 3) * 3
(x...x + 3).each do |i|
(y...y + 3).each do |j|
tiles << self[[i, j]]
end
end
tiles
end
def squares
(0..8).to_a.map { |i| square(i) }
end
private
attr_reader :grid
end