Gaucheで魔方陣に挑戦その5
とりあえず 一番素直そうで速そうなのを書いておく。
現時点では ワンライナーでつくってみた(rubyで魔方陣その3) - 計算機と戯れる日々とかhaskellで魔方陣その2 - 計算機と戯れる日々と同じアルゴリズム
(use srfi-1) (use util.combinations) (use util.match) (define-syntax =2 (syntax-rules () ((=2) #f) ((=2 t) t) ((=2 t1 t2) (let ((x t1)(y t2)) (if (eq? x y) x #f))) ((=2 t1 t2 t3 ...) (let ((x (=2 t1 t2))) (if x (=2 x t3 ...) #f))))) (permutations-for-each (lambda (x) (if ((match-lambda ((a b c d e f g h i)(=2 (+ a b c) (+ d e f) (+ g h i) (+ a d g) (+ b e h) (+ c f i) (+ a e i) (+ c e g)))) x) (print x))) (iota 9 1))
$ time gosh g.scm (2 7 6 9 5 1 4 3 8) (2 9 4 7 5 3 6 1 8) (4 3 8 9 5 1 2 7 6) (4 9 2 3 5 7 8 1 6) (6 1 8 7 5 3 2 9 4) (6 7 2 1 5 9 8 3 4) (8 1 6 3 5 7 4 9 2) (8 3 4 1 5 9 6 7 2) real 0m1.754s user 0m1.740s sys 0m0.016s
追記 2008/12/10 10:17:11:
(apply (lambda (a b c d...) ..) x)で修正した
(use srfi-1) (use util.combinations) (define-syntax =2 (syntax-rules () ((=2) #f) ((=2 t) t) ((=2 t1 t2) (let ((x t1)(y t2)) (if (eq? x y) x #f))) ((=2 t1 t2 t3 ...) (let ((x (=2 t1 t2))) (if x (=2 x t3 ...) #f))))) (permutations-for-each (lambda (x) (if (apply (lambda (a b c d e f g h i) (=2 (+ a b c) (+ d e f) (+ g h i) (+ a d g) (+ b e h) (+ c f i) (+ a e i) (+ c e g))) x) (print x))) (iota 9 1))