Add new test - sudoku solver.
All checks were successful
The build was successful.

This commit is contained in:
Rafal Kupiec 2019-12-22 22:44:15 +01:00
parent 709b5971c6
commit 3eb82e632b
Signed by: belliash
GPG Key ID: 4E829243E0CFE6B4
2 changed files with 124 additions and 0 deletions

105
tests/sudoku_solver.aer Normal file
View File

@ -0,0 +1,105 @@
import 'math';
class Sudoku {
public int[] $board;
int $size;
public void __construct(int[] $board) {
$this->board = $board;
$this->size = sizeof($this->board);
}
public bool isSafe(int $row, int $col, int $n) {
for(int $d = 0; $d < $this->size; $d++) {
if($this->board[$row][$d] == $n) {
return false;
}
}
for(int $r = 0; $r < $this->size; $r++) {
if($this->board[$r][$col] == $n) {
return false;
}
}
int $sqrt = (int) sqrt($this->size);
int $boxRowStart = $row - $row % $sqrt;
int $boxColStart = $col - $col % $sqrt;
for(int $w = $boxRowStart; $w < $boxRowStart + $sqrt; $w++) {
for(int $q = $boxColStart; $q < $boxColStart + $sqrt; $q++) {
if($this->board[$w][$q] == $n) {
return false;
}
}
}
return true;
}
public void print() {
for(int $r = 0; $r < $this->size; $r++) {
for(int $d = 0; $d < $this->size; $d++) {
print($this->board[$r][$d] + " ");
}
print("\n");
}
}
public bool solve() {
int $row = -1;
int $col = -1;
bool $isEmpty = true;
for(int $i = 0; $i < $this->size; $i++) {
for(int $j = 0; $j < $this->size; $j++) {
if($this->board[$i][$j] == 0) {
$row = $i;
$col = $j;
$isEmpty = false;
break;
}
}
if(!$isEmpty) {
break;
}
}
if($isEmpty) {
return true;
}
for(int $n = 1; $n <= $this->size; $n++) {
if($this->isSafe($row, $col, $n)) {
$this->board[$row][$col] = $n;
if($this->solve()) {
return true;
} else {
$this->board[$row][$col] = 0;
}
}
}
return false;
}
}
class Program {
void main() {
int[] $board = {
{3, 0, 6, 5, 0, 8, 4, 0, 0},
{5, 2, 0, 0, 0, 0, 0, 0, 0},
{0, 8, 7, 0, 0, 0, 0, 3, 1},
{0, 0, 3, 0, 1, 0, 0, 8, 0},
{9, 0, 0, 8, 6, 3, 0, 0, 5},
{0, 5, 0, 0, 9, 0, 6, 0, 0},
{1, 3, 0, 0, 0, 0, 2, 5, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0}
};
object $sudoku = new Sudoku($board);
$sudoku->print();
print("=================\n");
if($sudoku->solve()) {
$sudoku->print();
} else {
print("No solution found\n");
$sudoku->print();
}
}
}

19
tests/sudoku_solver.exp Normal file
View File

@ -0,0 +1,19 @@
3 0 6 5 0 8 4 0 0
5 2 0 0 0 0 0 0 0
0 8 7 0 0 0 0 3 1
0 0 3 0 1 0 0 8 0
9 0 0 8 6 3 0 0 5
0 5 0 0 9 0 6 0 0
1 3 0 0 0 0 2 5 0
0 0 0 0 0 0 0 7 4
0 0 5 2 0 6 3 0 0
=================
3 1 6 5 7 8 4 9 2
5 2 9 1 3 4 7 6 8
4 8 7 6 2 9 5 3 1
2 6 3 4 1 5 9 8 7
9 7 4 8 6 3 1 2 5
8 5 1 7 9 2 6 4 3
1 3 8 9 4 7 2 5 6
6 9 2 3 5 1 8 7 4
7 4 5 2 8 6 3 1 9