( * * LANGUAGE : ANS Forth * PROJECT : Forth Environments * DESCRIPTION : Magic squares demo * CATEGORY : Example * AUTHOR : Erwin Dondorp, August 19, 1991 * LAST CHANGE : March 6, 1993, Marcel Hendrix, Ansification * LAST CHANGE : October 10, 1991, Marcel Hendrix * ) MARKER -magic DECIMAL ( * Magic squares by Erwin Dondorp after a widely known algorithm: - Start with value one in upper middle cell. - next cell is one up and to the right, use circular wrap when passing edges - if this cell is occupied, move one cell down - if this cell is also occupied, stop * ) 0 VALUE ORDER 0 VALUE COL 0 VALUE ROW 0 VALUE ADDR 0 VALUE THERE : MAGIC \ --- <> TO ORDER ORDER 1 AND 0 = ABORT" Value should be odd" ORDER 99 > ORDER 3 < OR ABORT" Value should be between 3 and 99" ALIGN HERE TO ADDR ORDER DUP * CELLS DUP TO THERE ALLOT ADDR ORDER DUP * CELLS ERASE ORDER 2 / TO COL 0 TO ROW ORDER DUP * 1 + 1 DO I ROW ORDER * COL + CELLS ADDR + ! ROW 1- TO ROW COL 1+ TO COL COL ORDER < INVERT ( >= ) IF ORDER NEGATE COL + TO COL THEN ROW 0 < IF ORDER ROW + TO ROW THEN ROW ORDER * COL + CELLS ADDR + @ IF ROW 2 + TO ROW COL 1 - TO COL ROW ORDER MOD TO ROW COL ORDER + ORDER MOD TO COL THEN LOOP CR ." Magic square " ORDER DUP 0 .R [CHAR] x EMIT . CR ORDER 0 DO ORDER 0 CR DO ADDR J CELLS ORDER * + I CELLS + @ ORDER DUP * S>D <# #S #> NIP .R SPACE LOOP LOOP CR CR ." Sum = " ORDER DUP DUP * * ORDER + 2 / . THERE NEGATE ALLOT ; : HELP CR ." MAGIC for a magic square n*n" CR ." must be odd, >= 3, <= 99" CR ." > 19 will be too wide for the screen" ; HELP CR ( * End of Source * )