Last active
November 8, 2018 13:05
-
-
Save tounsils/7bf1d16034d777d44e94e6532718817e to your computer and use it in GitHub Desktop.
Function that tests if the suduko is solvedor no
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: Tounsi | |
* Date: 30/10/2018 | |
* Time: 11:59 | |
*/ | |
Function used_in_row($grid, $row, $num) | |
{ | |
$used = 0; | |
for ($col = 0; $col < 9; $col++){ | |
if ($grid[$row][$col] == $num) { $used++;} | |
if ($used > 1) { | |
return true; | |
} | |
} | |
return false; | |
} | |
Function used_in_col($grid, $col, $num) | |
{ | |
$used = 0; | |
for ($row = 0; $row < 9; $row++){ | |
if ($grid[$row][$col] == $num) { $used++;} | |
if ($used > 1) { | |
return true; | |
} | |
} | |
return false; | |
} | |
Function used_in_box($grid, $box_start_row, $box_start_col, $num) | |
{ | |
$used = 0; | |
for ($row = 0; $row < 3; $row++) { | |
for ($col = 0; $col < 3; $col++) | |
{ | |
$used = 0; | |
if ($grid[$row + $box_start_row][$col + $box_start_col] == $num) { | |
$used++; | |
} | |
if ($used > 1) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
Function is_safe($grid, $row, $col, $num) | |
{ | |
// Check if 'num' is not already placed in current row, | |
// current column and current 3x3 box | |
$res = | |
((!used_in_row($grid, $row, $num)) | |
&& (!used_in_col($grid, $col, $num)) | |
&& (!used_in_box($grid, $row - ($row % 3), $col - ($col % 3), $num))); | |
return $res; | |
} | |
function displayArray($arr){ | |
for ($i = 0; $i < 9; $i++){ | |
for ($j = 0; $j < 9; $j++){ | |
if (($j)%3 == 0) {echo "|";} | |
echo $arr[$i][$j] . " "; | |
} | |
if (($i+1)%3 == 0) {echo "<br>----------------------";} | |
echo "<br>"; | |
} | |
} | |
function testSudoku($arr){ | |
for ($row = 0; $row < 9; $row++) { | |
for ($col = 0; $col < 9; $col++) { | |
if (($arr[$row][$col] == 0) ) { | |
echo "[$row][$col] = zero"; | |
return false; | |
} | |
if (!(is_safe($arr, $row, $col, $arr[$row][$col]))) { | |
echo "[$row][$col] = " . $arr[$row][$col] . " (Value used more than once!)"; | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
$grid = array( | |
array(2, 3, 4, 1, 7, 8, 6, 5, 9, ), | |
array(7, 8, 6, 3, 5, 9, 1, 4, 2, ), | |
array(9, 5, 1, 6, 4, 2, 3, 8, 7, ), | |
array(3, 7, 2, 4, 9, 6, 8, 1, 5, ), | |
array(5, 1, 9, 8, 3, 7, 2, 6, 4, ), | |
array(4, 6, 8, 5, 2, 1, 9, 7, 3, ), | |
array(8, 2, 3, 7, 1, 5, 4, 9, 6, ), | |
array(6, 9, 7, 2, 8, 4, 5, 3, 1, ), | |
array(1, 4, 5, 9, 6, 3, 7, 8, 8, ) | |
); | |
displayArray($grid); | |
$res = testSudoku($grid); | |
echo "<br>"; | |
if ($res){ | |
echo "Complete"; | |
} | |
else{ | |
echo "No "; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment