* N queens problem, a string oriented version to * demonstrate the power of pattern matching. * A numerically oriented version will run faster than this. * Program written by Viktors Berstis N = 5 NM1 = N - 1; NP1 = N + 1; NSZ = N * NP1; &STLIMIT = 10 ** 9; &ANCHOR = 1 DEFINE('SOLVE(B)I') * This pattern tests if the first queen attacks any of the others: TEST = BREAK('Q') 'Q' (ARBNO(LEN(N) '-') LEN(N) 'Q' + | ARBNO(LEN(NP1) '-') LEN(NP1) 'Q' + | ARBNO(LEN(NM1) '-') LEN(NM1) 'Q') P = LEN(NM1) . X LEN(1); L = 'Q' DUPL('-',NM1) ' ' SOLVE() :(END) SOLVE EQ(SIZE(B),NSZ) :S(PRINT) * Add another row with a queen: B = L B LOOP I = LT(I,N) I + 1 :F(RETURN) B TEST :S(NEXT) SOLVE(B) * Try queen in next square: NEXT B P = '-' X :(LOOP) PRINT SOLUTION = SOLUTION + 1 OUTPUT = 'Solution number ' SOLUTION ' is:' PRTLOOP B LEN(NP1) . OUTPUT = :S(PRTLOOP)F(RETURN) END