Gaucheで魔方陣に挑戦その4

Gaucheで魔方陣に挑戦その4

haskellでパターンマッチを教えてもらったのでgaucheにもmatch-lambdaがあったのを思い出した。

素直に組んでみる

(use srfi-1)
(use util.combinations)
(use util.match)
(map print (filter
	(match-lambda ((a b c d e f g h i)(= (+ a b c) (+ d e f) (+ g h i) (+ a d g) (+ b e h) (+ c f i) (+ a e i) (+ c e g))))
	(permutations (iota 9 1))))

よし。

$ time gosh f.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	0m4.295s
user	0m4.244s
sys	0m0.052s

やっぱ、遅いなぁ。

=の高速化を図る

(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)))))
(map print (filter
	(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))))
	(permutations (iota 9 1))))
$ time gosh f.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	0m3.980s
user	0m3.948s
sys	0m0.028s

うーん。もう止めよう。この辺で諦めよう。
後やれることはGaucheで魔方陣に挑戦その3 - 計算機と戯れる日々との組み合わせだもんな。
ソースが読めたもんじゃなかった。