J2EE之巔

           

          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 on 2012-11-26 12:21 超越巔峰 閱讀(2844) 評論(0)  編輯  收藏 所屬分類: Clojure


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          導航

          統計

          常用鏈接

          留言簿(12)

          隨筆分類(54)

          隨筆檔案(59)

          文章分類(2)

          文章檔案(1)

          相冊

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 佛冈县| 凉山| 旅游| 阿鲁科尔沁旗| 谢通门县| 洱源县| 绥化市| 木兰县| 正宁县| 多伦县| 东辽县| 赣榆县| 连云港市| 东港市| 旅游| 自治县| 九江市| 滦平县| 普宁市| 苍南县| 乃东县| 资溪县| 桃园市| 蒙阴县| 棋牌| 吉林省| 南岸区| 涿鹿县| 富阳市| 惠来县| 靖边县| 阿克陶县| 全州县| 定结县| 元朗区| 延庆县| 社会| 静海县| 西乌| 阿拉尔市| 长乐市|