1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

n-queen問題をcommon lispで解く

1
Posted at

n-queen問題をcommon lispで解く:octopus:
SBCL 2.6.4

コード

solve-n-queen-problem.lisp
(defun solve-n-queen-problem (n is-print &optional (result-num 0) (right-bit 0) (left-bit 0) (col-bit 0))
    (if (plusp (ash result-num (- n (* n n)))) (or (and is-print (print result-num)) nil))
    (loop for i fixnum from 0 below n do
        (let ((mdl-bit (ash 1 i)))
            (declare (fixnum mdl-bit))
            (unless (or (plusp (logand mdl-bit col-bit)) (plusp (logand mdl-bit right-bit)) (plusp (logand mdl-bit left-bit)))
                (solve-n-queen-problem n is-print (logior (ash result-num n) mdl-bit) (ash (logior mdl-bit right-bit) 1) (ash (logior mdl-bit left-bit) -1) (logior mdl-bit col-bit))))))

ベンチマーク

3回ずつ測定。

n (ms) avg
10 5.147 /4.074 /4.953 4.725
11 18.12 /18.016 /20.933 19.023
12 84.506 /82.567 /84.557 83.877
13 461.826 /451.484 /453.13998 455.483
14 2744.004 /2745.979 /2731.4119 2740.465
15 17257.926 /17296.436 /17259.926 17271.429

説明

n-queen問題では、盤面(n*nのmatrix)について、各行にそれぞれqueenが1つずつ配置されていれば良い、とまず考えることができる。
それを再帰で実装しつつ、配置不可能なマスには配置しないよう、都度枝打ちしていこうというアプローチ。

8-queen等、特定の数に特化して関数を作るよりかは若干遅くなる。
これはnを動的に持つことによる最適化不能が1つ原因。
それを踏まえつつ、以下の部分に注意してブラッシュアップを進めていった。
・exptではなくashを使うようにする
・memberは使わない
・fixnumを使う。徹底してるわけではないが……。

また結果は全てビットに寄せて持たせている。
出力させてもヒトの目からは何のこっちゃの数字が並ぶが、リストなどで持つよりも早い。
ので座標や通番表示にするには別途デコードが必要となる。

枝打ちについては特に言及無し。別段トリッキーなことをしているわけではない。

感想ほか

楽しかった(小並感
ビットボードの扱いには大分慣れてきた感がある。
common lispに入門して1ヶ月ちょい経つけど、こういう系のものばっか書いてる今日この頃。
前に書いたライフゲームがそこらで拾った野良コードに大差でスコア負けしてるので、今はその見直し中。
ログ解析用のちょっとした汎用DSLとかそういう"実用寄り"のものも作ってみたい欲もあるけど、軽い気持ちで手を出した結果反撃にあったのでしばらくは遊んでいる予定……。
あんま焦らず行こうね。

thanks for reading!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?