J2EE之巔

           

          2012年11月26日

          The Clojure Program To solve N Queens Problem (Without back tracing)

          Not like the previous solution here http://www.aygfsteel.com/chaocai/archive/2012/08/05/384844.html
          The following solution not using the back tracing way is more concise and readable, but for the searching space becomes huger, the performance is much worser then the previous one.

          (ns SICP.unit3)
          (defn conflictInCol? [s col]
            (some #(= col %) s)
          )

          (defn conflictInDia? [s col]
            (let [dia (count s)
                  n1 (fn [c
          ] (Math/abs (- dia (.indexOf s c))))
                  n2 (fn [c] (Math/abs (- col c)))]
              (some #(= (n1 %) (n2 %)) s)
            )
          )

          (defn safe? [s col] 
            (not (or (conflictInCol? s col) (conflictInDia? s col)))
          )
            
          (defn next-level-queens [solutions-for-prev-level board-size current-level]
            (let [solutions (atom [])]
              (doseq [s solutions-for-prev-level]
                (doseq [col (range 0 board-size)]
                  (if (safe? s col)
                    (reset! solutions (cons (conj s col) @solutions))
               
                  )
                 )
             
              )
             
                (if (< current-level (dec board-size))
                  (recur @solutions board-size (inc current-level))
                  (count @solutions)
                )
             )
          )

          (defn queens [board-size]
            (next-level-queens  (apply vector (map #(vector %) (range 0 board-size))) board-size 1)
          )

          Chao Cai (蔡超)
          Sr. SDE
          Amazon


           

          posted @ 2012-11-26 12:21 超越巔峰 閱讀(2843) | 評論 (0)編輯 收藏

          導航

          統計

          常用鏈接

          留言簿(12)

          隨筆分類(54)

          隨筆檔案(59)

          文章分類(2)

          文章檔案(1)

          相冊

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 利津县| 扎鲁特旗| 福建省| 道孚县| 揭阳市| 奉新县| 察雅县| 应用必备| 张家界市| 临洮县| 沙河市| 汕尾市| 新乐市| 台安县| 鄱阳县| 抚远县| 沙河市| 军事| 探索| 吴堡县| 东安县| 衡东县| 卢湾区| 荥经县| 滕州市| 固安县| 咸宁市| 平舆县| 开鲁县| 蒙自县| 本溪市| 永安市| 佛坪县| 黑山县| 镇平县| 崇州市| 维西| 抚顺县| 阳曲县| 铁力市| 保定市|