This popular Japanese number puzzle has just one easy rule:
In every Row, every Column and every 3x3 sub-grid, all the numbers from 1 to 9 should appear, but only once in each row, column and sub-grid.
+------+-------+------+
| 0 0 0 | 7 0 0 | 4 0 0 |
| 0 3 0 | 0 9 0 | 0 2 0 |
| 4 0 0 | 0 0 5 | 0 0 0 |
+------+-------+------+
| 0 0 8 | 0 0 0 | 0 0 5 |
| 0 9 0 | 0 3 0 | 0 7 0 |
| 6 0 0 | 0 0 0 | 3 0 0 |
+------+-------+------+
| 0 0 0 | 4 0 0 | 0 0 6 |
| 0 7 0 | 0 2 0 | 0 9 0 |
| 0 0 5 | 0 0 8 | 0 0 0 |
+------+-------+------+
Replace the 0's with the digits required to satisfy the rule.
DECLARE SUB find (v!, h!)
DATA 000700400
DATA 030090020
DATA 400005000
DATA 008000005
DATA 090030070
DATA 600000300
DATA 000400006
DATA 070020090
DATA 005008000
CLEAR , , 10000
CLS
PRINT TIMER
FOR i = 1 TO 9
READ l$(i)
NEXT
DIM SHARED b(9, 9)
FOR i = 1 TO 9
FOR j = 1 TO 9
b(i, j) = VAL(MID$(l$(i), j, 1))
NEXT
NEXT
find 1, 1
PRINT TIMER
SUB find (v, h)
IF b(v, h) = 0 THEN
x = 0: y = x
FOR trial = 1 TO 9
good = 1
FOR i = 1 TO 9
IF b(v, i) = trial OR b(i, h) = trial THEN good = 0
NEXT i
IF good THEN
v1 = INT((v - 1) / 3) * 3 + 1
h1 = INT((h - 1) / 3) * 3 + 1
FOR i = v1 TO v1 + 2
FOR j = h1 TO h1 + 2
IF b(i, j) = trial THEN good = 0
NEXT
NEXT
IF good THEN
b(v, h) = trial
GOSUB incrCoords
b(v, h) = 0
END IF
END IF
NEXT trial
ELSE
GOSUB incrCoords
END IF
EXIT SUB
incrCoords:
hnew = h + 1
IF hnew > 9 THEN
vnew = v + 1: hnew = 1
ELSE
vnew = v
END IF
IF vnew > 9 THEN
FOR i = 1 TO 9
FOR j = 1 TO 9
PRINT b(i, j);
NEXT
PRINT
NEXT
PRINT TIMER
ELSE
find vnew, hnew
END IF
RETURN
END SUB
Finds
1 5 2 7 8 3 4 6 9
7 3 6 1 9 4 5 2 8
4 8 9 2 6 5 7 3 1
3 2 8 6 4 7 9 1 5
5 9 1 8 3 2 6 7 4
6 4 7 9 5 1 3 8 2
2 1 3 4 7 9 8 5 6
8 7 4 5 2 6 1 9 3
9 6 5 3 1 8 2 4 7
|
Posted by Charlie
on 2005-05-13 21:03:15 |