Class: Sudoku::Grid
- Inherits:
-
Object
- Object
- Sudoku::Grid
- Defined in:
- lib/sudoku/grid.rb,
lib/sudoku/grid/cell.rb
Defined Under Namespace
Classes: Cell
Instance Method Summary collapse
- #[]=(column, row, value) ⇒ Object
- #cells ⇒ Object
- #column(cell) ⇒ Object
- #filled_cells ⇒ Object
-
#initialize(string = nil) ⇒ Grid
constructor
A new instance of Grid.
- #row(cell) ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(string = nil) ⇒ Grid
Returns a new instance of Grid.
5 6 7 8 9 10 11 12 13 |
# File 'lib/sudoku/grid.rb', line 5 def initialize(string=nil) @rows = if string string.split($/).collect { |row| row.split(',').collect { |value| Cell.new(self, value.to_i) } } else (1..9).collect { |n| [] } end end |
Instance Method Details
#[]=(column, row, value) ⇒ Object
15 16 17 |
# File 'lib/sudoku/grid.rb', line 15 def []=(column, row, value) @rows[row - 1][column - 1] = value end |
#cells ⇒ Object
19 20 21 |
# File 'lib/sudoku/grid.rb', line 19 def cells @rows.flatten end |
#column(cell) ⇒ Object
27 28 29 30 |
# File 'lib/sudoku/grid.rb', line 27 def column(cell) row = @rows.find { |r| r.include?(cell) } row.index(cell) + 1 end |
#filled_cells ⇒ Object
23 24 25 |
# File 'lib/sudoku/grid.rb', line 23 def filled_cells cells.select { |c| c.filled? } end |
#row(cell) ⇒ Object
32 33 34 35 |
# File 'lib/sudoku/grid.rb', line 32 def row(cell) row = @rows.find { |r| r.include?(cell) } @rows.index(row) + 1 end |
#to_s ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/sudoku/grid.rb', line 37 def to_s row_divider = (1..3).collect { "\e[37m---|---|---\e[0m" }.join('|') row_divider = "\n#{row_divider}\n" row_group_divider = (1..3).collect { '-' * 11 }.join('+') row_group_divider = "\n#{row_group_divider}\n" [0..2, 3..5, 6..8].collect { |row_group| @rows[row_group].collect { |row| [0..2, 3..5, 6..8].collect { |col_group| col_group.collect { |column| " #{row[column] || ' '} " }.join("\e[37m|\e[0m") }.join('|') }.join(row_divider) }.join(row_group_divider) end |