From 61bbd00f6d17ade5bf4feaf49b8192ae38d0d00f Mon Sep 17 00:00:00 2001 From: Alberto Venturini Date: Mon, 28 Oct 2019 21:33:45 +0200 Subject: [PATCH] Add functions to extract rows, colums and blocks --- spec/board_spec.cr | 33 +++++++++++++++++++++++++++++++-- src/board.cr | 43 +++++++++++++++++++++++++++++++++---------- 2 files changed, 64 insertions(+), 12 deletions(-) diff --git a/spec/board_spec.cr b/spec/board_spec.cr index 092142d..aa53a45 100644 --- a/spec/board_spec.cr +++ b/spec/board_spec.cr @@ -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 diff --git a/src/board.cr b/src/board.cr index 9a45cc8..7dcd152 100644 --- a/src/board.cr +++ b/src/board.cr @@ -1,27 +1,50 @@ module Sudoku + class BoardException < Exception + end + class Board - alias Value = Nil | Int8 - - enum State - Valid - Invalid - end + 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