Add functions to extract rows, colums and blocks

This commit is contained in:
Alberto Venturini 2019-10-28 21:33:45 +02:00
parent 895a9dd01b
commit 61bbd00f6d
2 changed files with 64 additions and 12 deletions

View file

@ -3,14 +3,43 @@ require "./spec_helper"
describe Sudoku::Board do
it "initialized grid with nil values" do
board = Sudoku::Board.new(8, 8)
board = Sudoku::Board.new(9, 3)
board.get(0, 0).should eq nil
end
it "raises exception if board size is not divisible by block size" do
expect_raises(Sudoku::BoardException) do
Sudoku::Board.new(9, 4)
end
end
it "puts numbers correctly" do
board = Sudoku::Board.new(8, 8)
board = Sudoku::Board.new(9, 3)
board.put(1, 0, 0)
board.get(0, 0).should eq 1
end
it "extracts rows correctly" do
row = 1
board = Sudoku::Board.new(4, 2)
(0..3).each { |i| board.put(i, i, row) }
board.extract_row(row).should eq [0, 1, 2, 3]
end
it "extracts columns correctly" do
column = 2
board = Sudoku::Board.new(4, 2)
(0..3).each { |i| board.put(i, column, i) }
board.extract_column(column).should eq [0, 1, 2, 3]
end
it "extracts blocks correctly" do
board = Sudoku::Board.new(4, 2)
board.put(42, 2, 0)
board.put(43, 3, 0)
board.put(44, 2, 1)
board.put(45, 3, 1)
board.extract_block(3, 1).should eq [[42, 43], [44, 45]]
end
end

View file

@ -1,27 +1,50 @@
module Sudoku
class Board
alias Value = Nil | Int8
enum State
Valid
Invalid
class BoardException < Exception
end
class Board
alias Value = Nil | Int32
@grid : Array(Array(Value))
getter grid
def initialize(@width : Int8, @height : Int8)
@grid = Array(Value).new(@width * @height, nil)
def initialize(@size : Int32, @block_size : Int32)
raise BoardException.new() unless @size.divisible_by?(@block_size)
@grid = Array(Array(Value)).new(@size) { Array(Value).new(@size, nil) }
end
def put(value : Value, x, y)
@grid[y * @width + x] = value
@grid[y][x] = value
end
def get(x, y)
@grid[y * @width + x]
@grid[y][x]
end
def check_valid(value : Value, x, y)
end
def extract_row(y)
@grid[y]
end
def extract_column(x)
(0..@size - 1).map { |i| get(x, i) }
end
def extract_block(x, y)
block_start_x = x - (x % @block_size)
block_start_y = y - (y % @block_size)
(block_start_y..block_start_y + @block_size - 1).map { |j|
(block_start_x..block_start_x + @block_size - 1).map { |i|
get(i, j)
}
}
end
end