Arrange the digits 1-9 in a 3x3 square using each once only according to the following rules:
- Exactly one prime is directly above a prime two less.
- Each pair of opposite corners sums to the same square total and exactly two columns share another square total.
- Exactly one prime is directly to the left of a non-prime two greater.
- Directly above exactly one square digit is a digit four greater.
- Directly to the right of exactly one cubic digit is a digit one greater.
By rule 1, a 7 has to be over a 5 or a 5 over a 3.
The pairs satisfying rule 3 could be 2,4 or 7,9.
By rule 4, either 8 is above 4 or 5 above 1.
The pairs satisfying rule 5 are 1,2 or 8,9.
The following program looks for such, as well as most of rule 2:
DECLARE SUB permute (a$)
CLS
s$ = "123456789"
FOR i = 1 TO 362880
bad = 1
ix = INSTR(s$, "7")
IF ix < 7 THEN IF MID$(s$, ix + 3, 1) = \"5\" THEN bad = 0
ix = INSTR(s$, \"5\")
IF ix < 7 THEN IF MID$(s$, ix + 3, 1) = \"3\" THEN bad = 0
IF bad THEN GOTO notThis
bad = 1
ix = INSTR(s$, \"8\")
IF ix < 7 THEN IF MID$(s$, ix + 3, 1) = \"4\" THEN bad = 0
ix = INSTR(s$, \"5\")
IF ix < 7 THEN IF MID$(s$, ix + 3, 1) = \"1\" THEN bad = 0
IF bad THEN GOTO notThis
bad = 1
ix = INSTR(s$, \"2\")
IF ix MOD 3 THEN IF MID$(s$, ix + 1, 1) = \"4\" THEN bad = 0
ix = INSTR(s$, \"7\")
IF ix MOD 3 THEN IF MID$(s$, ix + 1, 1) = \"9\" THEN bad = 0
IF bad THEN GOTO notThis
bad = 1
ix = INSTR(s$, \"1\")
IF ix MOD 3 THEN IF MID$(s$, ix + 1, 1) = \"2\" THEN bad = 0
ix = INSTR(s$, \"8\")
IF ix MOD 3 THEN IF MID$(s$, ix + 1, 1) = \"9\" THEN bad = 0
IF bad THEN GOTO notThis
sqCt = 0
FOR col = 1 TO 3
t(col) = 0
FOR row = 1 TO 3
t(col) = t(col) + VAL(MID$(s$, (row - 1) * 3 + col, 1))
NEXT
sqrt = INT(SQR(t(col)) + .5)
IF sqrt * sqrt = t(col) THEN sqCt = sqCt + 1: sq(sqCt) = t(col)
NEXT
IF sqCt < 2 THEN GOTO notThis
IF sq(1) <> sq(2) THEN GOTO notThis
p1 = VAL(MID$(s$, 1, 1)) + VAL(MID$(s$, 9, 1))
p2 = VAL(MID$(s$, 3, 1)) + VAL(MID$(s$, 7, 1))
IF p1 <> p2 THEN GOTO notThis
PRINT MID$(s$, 1, 3)
PRINT MID$(s$, 4, 3)
PRINT MID$(s$, 7, 3)
PRINT
notThis:
permute s$
NEXT
SUB permute (a$)
DEFINT A-Z
x$ = ""
FOR i = LEN(a$) TO 1 STEP -1
l$ = x$
x$ = MID$(a$, i, 1)
IF x$ < l$ THEN EXIT FOR
NEXT
IF i = 0 THEN
FOR j = 1 TO LEN(a$) \ 2
x$ = MID$(a$, j, 1)
MID$(a$, j, 1) = MID$(a$, LEN(a$) - j + 1, 1)
MID$(a$, LEN(a$) - j + 1, 1) = x$
NEXT
ELSE
FOR j = LEN(a$) TO i + 1 STEP -1
IF MID$(a$, j, 1) > x$ THEN EXIT FOR
NEXT
MID$(a$, i, 1) = MID$(a$, j, 1)
MID$(a$, j, 1) = x$
FOR j = 1 TO (LEN(a$) - i) \ 2
x$ = MID$(a$, i + j, 1)
MID$(a$, i + j, 1) = MID$(a$, LEN(a$) - j + 1, 1)
MID$(a$, LEN(a$) - j + 1, 1) = x$
NEXT
END IF
END SUB
and finds
789
524
163
897
635
241
The first does not satisfy the perfect square condition of the sums of opposite corners, so the latter is the solution.
|
Posted by Charlie
on 2003-12-29 10:42:54 |