0
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?

部分和問題への入門(common lisp)

0
Posted at

部分和問題への入門(common lisp):octopus:
SBCL 2.6.4

経緯

少し前から考えている問題があって、どうにも行き詰って調べると部分和問題の亜種みたいなものに分類できるらしかった。
最初からテクニカルな解き方を求めている自分に気付き、じゃあまずはベーシックなことからやってみようということで、
総当たり法を用いた部分和問題の解決を実装してみるかという運びになった。

コード

partial-sum-bitsearch.lisp
(defun partial-sum-bitsearch (arr target)
    (let* ((len (length arr)))
        (loop for i from 0 below (ash 1 len) do
            (let ((p-sum 0))
                (loop for j from 0 below len do
                    (setf p-sum (+ p-sum (* (aref arr j) (ash (logand (ash 1 j) i) (- j))))))
                (if (= p-sum target) (format t "pattern:~a~%" i))))))
partial-sum-bitsearch(結果をビットで表示するver).lisp
(defun partial-sum-bitsearch (arr target)
    (let* ((len (length arr)))
        (loop for i from 0 below (ash 1 len) do
            (let ((p-sum 0))
                (loop for j from 0 below len do
                    (setf p-sum (+ p-sum (* (aref arr j) (ash (logand (ash 1 j) i) (- j))))))
                (if (= p-sum target) (format t "pattern:~v,'0b~%" len i))))))                

bitの並びと配列の並び順が逆であることだけに注意。揃えたかったらjを全部len-jに変えれば良いのかな。

実行結果(ビットで表示するver)

折り畳み
* (partial-sum-bitsearch #(1 2 3 4 5 6 7 8 9 10) 0)
pattern:0000000000
NIL
* (partial-sum-bitsearch #(1 2 3 4 5 6 7 8 9 10) 55)
pattern:1111111111
NIL
* (partial-sum-bitsearch #(1 2 3 4 5 6 7 8 9 10) 56)
NIL
* (partial-sum-bitsearch #(1 2 3 4 5 6 7 8 9 10) 11)
pattern:0000010111
pattern:0000011010
pattern:0000100110
pattern:0000101001
pattern:0000110000
pattern:0001000101
pattern:0001001000
pattern:0010000011
pattern:0010000100
pattern:0100000010
pattern:1000000001
NIL

説明

要素数Lの配列に対しその部分和を求める場合、その要素の組み合わせは2^L通りのパターンが存在する。
これは各要素をビットに見立てた場合の、それらのオンオフパターンの個数に等しい。

この総当たり方法は、2^L通りのパターンをループで試行し、各パターンに対応する部分和がターゲットとなる数と一致するかをチェックする。

最初に書いてみたコードでは、ループと再帰を組み合わせて使った都合順番違いによる重複を区別できず、
膨大な件数の合致パターンを出力する羽目になってしまった。
ちょっと考えて、別に再帰要らんなと気付く。

内側のループはビットパターンから部分和へとデコードしてるだけ。

(ash (logand (ash 1 j) i) (- j))

j桁目のビットが立ってたら1を返し、そうでなければ0を返す。
この方法は閃き豆電球で、当初は以下のように0埋めビット文字列にした後で、その要素を数字に変換するという手間を踏んでいた。
そっからlogandとifを絡めた方法を思いつき、最終的に上記のような形に落ち着いた。
こういうの思いつくときがいっちゃん楽しい。

; 当初のデコード方法
(let ... (char-bit-lst (coerce (format nil "~v,'0b" len i) 'list))
    ...
        (setf ... (digit-char-p (nth j char-bit-lst))))

感想ほか

今は動的計画法について書かれたブログなり記事なりを漁って読んでいる。
なるほどそうかという感想は浮かぶが、腹落ちしてないというのが実際のところ。
とりあえず脳みそに寝かせといて、納得が来るのを待つ。

thanks for reading!

0
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
0
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?