Grid A Grid B
A B C D A B C D
+---+---+---+---+ +---+---+---+---+
1 | | | | | 1 |14 |23 |34 |14 |
+---+---+---+---+ +---+---+---+---+
2 | | | | | 2 |31 |42 |26 |26 |
+---+---+---+---+ +---+---+---+---+
3 | | | | | 3 |22 |24 |44 |29 |
+---+---+---+---+ +---+---+---+---+
4 | | | | | 4 |12 |32 |19 |16 |
+---+---+---+---+ +---+---+---+---+
The numbers 1 to 16 are to be placed in grid A, so that consecutive numbers are not adjacent in any direction, including diagonally. Nor do they appear in the same row, column or any diagonal.
The number in each cell of grid B is the sum of the horizontal and vertical neighbors of the corresponding cell in grid A.
NB. The letters and numbers around the edge of the grid serve no purpose for the solver. They are to be used for identifying cells in the solution.
The first thing to realise is that B1+A2=14, so C2+B3=42-14=28. Similar pairs can be made from all four corners. This simplifies the programming, which then must also eventually test those such as A1+B2+C1 = 23, etc.
DIM used(16)
CLS
FOR b1 = 1 TO 13
a2 = 14 - b1
IF a2 <> b1 THEN
used(a2) = 1: used(b1) = 1
FOR c1 = 1 TO 13
d2 = 14 - c1
IF d2 <> c1 THEN
IF used(d2) = 0 AND used(c1) = 0 THEN
used(d2) = 1: used(c1) = 1
FOR b4 = 1 TO 11
a3 = 12 - b4
IF b4 <> a3 THEN
IF used(b4) = 0 AND used(a3) = 0 THEN
used(b4) = 1: used(a3) = 1
FOR c4 = 1 TO 15
d3 = 16 - c4
IF d3 <> c4 THEN
IF used(d3) = 0 AND used(c4) = 0 THEN
used(d3) = 1: used(c4) = 1
FOR c2 = 12 TO 16
b3 = 28 - c2
IF b3 <> c2 THEN
IF used(b3) = 0 AND used(c2) = 0 THEN
used(b3) = 1: used(c2) = 1
FOR c3 = 1 TO 11
b2 = 12 - c3
IF b2 <> c3 THEN
IF used(b2) = 0 AND used(c3) = 0 THEN
used(b2) = 1: used(c3) = 1
FOR a1 = 1 TO 16
IF used(a1) = 0 THEN
used(a1) = 1
FOR d1 = 1 TO 16
IF used(d1) = 0 THEN
used(d1) = 1
FOR a4 = 1 TO 16
IF used(a4) = 0 THEN
used(a4) = 1
FOR d4 = 1 TO 16
IF used(d4) = 0 THEN
used(d4) = 1
IF a1 + b2 + c1 = 23 AND b1 + c2 + d1 = 34 THEN
IF a1 + b2 + a3 = 31 AND a2 + b3 + a4 = 22 THEN
IF d1 + c2 + d3 = 26 AND d2 + c3 + d4 = 29 THEN
IF a4 + b3 + c4 = 32 AND b4 + c3 + d4 = 19 THEN
PRINT "."
PRINT USING "###"; a1; b1; c1; d1
PRINT USING "###"; a2; b2; c2; d2
PRINT USING "###"; a3; b3; c3; d3
PRINT USING "###"; a4; b4; c4; d4
END IF
END IF
END IF
END IF
used(d4) = 0
END IF
NEXT d4
used(a4) = 0
END IF
NEXT a4
used(d1) = 0
END IF
NEXT d1
used(a1) = 0
END IF
NEXT a1
used(b2) = 0: used(c3) = 0
END IF
END IF
NEXT
used(b3) = 0: used(c2) = 0
END IF
END IF
NEXT
used(d3) = 0: used(c4) = 0
END IF
END IF
NEXT
used(b4) = 0: used(a3) = 0
END IF
END IF
NEXT
used(d2) = 0: used(c1) = 0
END IF
END IF
NEXT
used(a2) = 0: used(b1) = 0
END IF
NEXT
The program did not make use of any of the caveats as to where consecutive numbers may not appear, yet a unique solution came out, satisfying those requirements.
The solution comes out:
15 10 1 8
4 7 16 13
9 12 5 2
6 3 14 11
|
Posted by Charlie
on 2006-10-26 16:11:07 |