Mailing List Archive: 49091 messages

## [REBOL] Re: Another coffee break problem?

### From: tomc:darkwing:uoregon at: 12-Nov-2003 23:23

```
On Tue, 11 Nov 2003, Joel Neely wrote:

> Hi, Gregg,
>
> Gregg Irwin wrote:
> >
> > JN> The following 3-by-3 display is a simple magic square:
> >
> > JN>          0  8  4
> > JN>          5  1  6
> > JN>          7  3  2
> >
> > JN> because each row and each column sums to 12...
> >
> > No diagonals? I thought magic squares had to work on the diagonal as
> > well? (not to be nit-picky or anything :)
> >
>
> To be equally picky ;-)
>
> That's why I said "simple magic" square instead of "totally magic".  I
> was going to post a follow-up problem to refine the first program so
> that it also checks diagonals.
>
> Also, not all sources I've looked at insist on diagonal operations.  One
> interesting way to generalize the problem is to "magic" rectangles with
> different height and width.  In that case, the definition of "diagonal"
> becomes more interesting...
>
> -jn-

ok here is my first pass, Im sure there is cleanup to do
have not done any benchmarking  ... time for bed

Rebol[
title: "magic square generator"
author: "Tom Conlin"
date: 12-Nov-2003
file: %itsawrap.r
version: 0.0.2
purpose: { Post from Joel Neely

The following 3-by-3 display is a simple magic square:

0  8  4
5  1  6
7  3  2

because each row and each column sums to 12.  Write a function
which uses the integers 0 thru 8 (once each!) to construct all
possible 3-by-3 simple magic squares.
Make it run as quickly as possible.
}
]

n: 3
ns: n * n

flip: func[b [series!] n[integer!]][ ; this one I like
forskip b n[reverse/part b n]
]

; not so happy with this, I finaly brute forced it
reflect: func [b [series!] n[integer!] /local t ][
t: make block! n * n
forskip b n[insert tail t pick b 1]
repeat i n - 1[
forskip b n[insert tail t pick b 1]
]
b: copy t
]

pprint: func[b [series!] n[integer!]][
loop n[print copy/part b n b: skip b n]
]

;; to be general these should be made functions
;; but with non 0  array origin it makes messy modulo math
ur: [8  9  7  2  3  1  5  6  4]
dn: [4  5  6  7  8  9  1  2  3]

s: t: 0
for i 1 ns 1 [
ms: copy [0 0 0 0 0 0 0 0 0]
s: i
poke ms s 1
for j 2 ns 1[
either equal? 0 pick ms t: pick ur s
[poke ms s: t j]
[poke ms s: pick dn s j]
]
b: copy ms
pprint b 3              ; normal
pprint flip b 3 3       ; about vertical axis
pprint reflect b 3 3    ; rotate left
pprint flip b 3 3       ; about backslash