From 83e5f7fff7463627cffdb03c985e34f5a47632ed Mon Sep 17 00:00:00 2001 From: miti99 Date: Mon, 16 Mar 2020 10:18:58 +0700 Subject: [PATCH] init commit --- sudoku.php | 596 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 596 insertions(+) create mode 100644 sudoku.php diff --git a/sudoku.php b/sudoku.php new file mode 100644 index 0000000..550b693 --- /dev/null +++ b/sudoku.php @@ -0,0 +1,596 @@ +grid = static::parseString($str, $emptySymbol); + $this->emptySymbol = $emptySymbol; + } + + public function solve() + { + try { + $this->placeNumber(0); + return false; + } catch (\Exception $e) { + return true; + } + } + + protected function placeNumber($pos) + { + if ($pos == 81) { + throw new \Exception("Finish"); + } + if ($this->grid[$pos] > 0) { + $this->placeNumber($pos + 1); + return; + } + for ($n = 1; $n <= 9; $n++) { + if ($this->checkValidity($n, $pos % 9, floor($pos / 9))) { + $this->grid[$pos] = $n; + $this->placeNumber($pos + 1); + $this->grid[$pos] = 0; + } + } + } + + protected function checkValidity($val, $x, $y) + { + for ($i = 0; $i < 9; $i++) { + if (($this->grid[$y * 9 + $i] == $val) || ($this->grid[$i * 9 + $x] == $val)) { + return false; + } + } + $startX = (int) ((int) ($x / 3) * 3); + $startY = (int) ((int) ($y / 3) * 3); + + for ($i = $startY; $i < $startY + 3; $i++) { + for ($j = $startX; $j < $startX + 3; $j++) { + if ($this->grid[$i * 9 + $j] == $val) { + return false; + } + } + } + return true; + } + + public function display() + { + $str = ""; + for ($i = 0; $i < 9; $i++) { + for ($j = 0; $j < 9; $j++) { + $str .= $this->grid[$i * 9 + $j]; + $str .= " "; + if ($j == 2 || $j == 5) { + $str .= "| "; + } + } + $str .= PHP_EOL; + if ($i == 2 || $i == 5) { + $str .= "------+-------+------" . PHP_EOL; + } + } + echo $str; + } + + public function __toString() + { + foreach ($this->grid as &$item) { + if ($item == 0) { + $item = $this->emptySymbol; + } + } + return implode("", $this->grid); + } +} +?> + + + + + + + + + + Solve Sudoku (Made by MiTiX) + + + + + + + +
+
+ +

Solve Sudoku (Made by MiTiX)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+ +
+
+ +

Input

+ + + + + + + + + +
value="" disabled >
+
+
+ solve(); + $output = (string) $solver; + ?> + +
+
+ +

Output

+ + + + + + + + + +
+
+
+ + + + + +
Made by @MiTiX +
source: https://rosettacode.org/wiki/Sudoku +
source: https://gist.github.com/thebinarypenguin/4d45ffe87096e508800b5d11544bf2fa \ No newline at end of file