docs
[mirrors/Programs.git] / php / skripty / sudoku_web.php
1 <form action="?" method="POST">
2 <textarea rows="9" cols="9" name="sudokupost">43 6 5 89
3 56 23
4 2 3
5 7 5 6 9 4
6 9 1
7 2 9 7 5 1
8 4 8
9 32 56
10 89 5 6 12</textarea>
11 <br /><input type="submit" value="Vyresit">
12 </form>
13
14 <?php
15 //Sudoku
16
17 //
18 function sudoku_print ($sudo) {
19 $sudo = str_replace(" ", ".", implode("\n", $sudo) );
20 $sudo = explode("\n", $sudo);
21 print_r($sudo);
22 }
23
24 //X line
25 //Y row
26
27 //
28 function sudoku_pos ($sudo, $x, $y) {
29 return($sudo[$x-1][$y-1]);
30 }
31 //
32 function sudoku_row ($sudo, $y) {
33 $row = "";
34 foreach ($sudo as $line) {
35 $row = ($row.$line[$y-1]);
36 }
37 return $row;
38 }
39 //
40 function sudoku_line ($sudo, $x) {
41 return $sudo[$x-1];
42 }
43 //
44 function sudoku_square ($sudo, $x, $y) {
45 if ( $x == 1 || $x == 2 || $x == 3 ) { $x = 1; }
46 if ( $x == 4 || $x == 5 || $x == 6 ) { $x = 4; }
47 if ( $x == 7 || $x == 8 || $x == 9 ) { $x = 7; }
48 if ( $y == 1 || $y == 2 || $y == 3 ) { $y = 1; }
49 if ( $y == 4 || $y == 5 || $y == 6 ) { $y = 4; }
50 if ( $y == 7 || $y == 8 || $y == 9 ) { $y = 7; }
51 //echo("\n$x\n$y\n");
52 $square = "";
53 $x--;
54 $y--;
55 $y0 = $y;
56
57 $i2 = 0;
58 while( $i2 < 3 ){
59 $i1 = 0;
60 $y = $y0;
61 while ( $i1 < 3 ){
62 $square = $square.$sudo[$x][$y];
63 $y++;
64 $i1++;
65 //echo("\n$x-$y");
66 }
67 $i2++;
68 $x++;
69 }
70 //echo("\n".$square);
71 return ($square);
72 }
73
74 //
75 function sudoku_candidates ($sudo, $x, $y) {
76 $cands = "123456789";
77 $donenums = ( sudoku_line($sudo, $x).sudoku_row($sudo, $y).sudoku_square($sudo, $x, $y) );
78 //echo $donenums;
79 //echo "\n\n";
80 //foreach ( $donenums as $del ) {
81 $indx = strlen($donenums)-1;
82 while ($indx >= 0) {
83 $del = $donenums[$indx];
84 //echo("!".$del);
85 $cands = str_replace($del, "", $cands);
86 $indx--;
87 }
88 //echo "\n\n".$cands;
89 return $cands;
90 }
91
92 //
93 function sudoku_compute($sudoku) {
94
95 $sudoku_old = "";
96 while( $sudoku_old != $sudoku ) {
97 $sudoku_old = $sudoku;
98
99 $is = sizeof($sudoku)-1;
100 while ($is >= 0) {
101 $line = $sudoku[$is];
102
103 $i = strlen($line)-1;
104 while ($i >= 0) {
105 //echo($line[$i]);
106
107 $cands = sudoku_candidates ( $sudoku, ($is+1), ($i+1) );
108 if ( strlen($cands) == 1 && !is_numeric($sudoku[$is][$i]) ) {
109 $sudoku[$is][$i] = $cands;
110 }
111
112 $i--;
113 }
114 //echo("\n");
115
116 $is--;
117 }
118 }
119 return($sudoku);
120 }
121
122 ///CODE///////////////////////////////////////////
123 /*
124 $sudoku = array(
125 "43 6 5 89",
126 "56 23",
127 " 2 3 ",
128 "7 5 6 9 4",
129 " 9 1 ",
130 "2 9 7 5 1",
131 " 4 8 ",
132 "32 56",
133 "89 5 6 12"
134 );
135 */
136
137 sudoku = explode ("\n",$_POST["sudokupost"]);
138
139
140 echo("Zadani:\n");
141 sudoku_print($sudoku);
142 echo("\nVysledek:\n");
143 sudoku_print(sudoku_compute($sudoku));
144
145 ?>
This page took 0.339634 seconds and 4 git commands to generate.