莊周夢蝶

          生活、程序、未來
             :: 首頁 ::  ::  :: 聚合  :: 管理
            看到這么一個題目:
              {3,2,2,6,7,8}排序輸出,7不在第二位,68不在一起。
           
            這樣的題目似乎避免不了遍歷,關(guān)鍵還在于過濾條件的安排,怎么讓過濾的范圍盡量地小。通常的做法是循環(huán)遍歷,對于類似Prolog這樣的語言來說,由于內(nèi)置了推理引擎,可以簡單地描述問題,讓引擎來幫你做遞歸遍歷,解決這類問題是非常簡單的。Prolog好久沒寫,以Ruby的amb操作符為例來解決這道題目:

          #結(jié)果為hash,去重
          $hash={}
          amb
          =Amb.new
          array
          =[3,2,2,6,7,8]
          class << array
           alias remove delete
           
          def delete(*nums)
             result
          =dup
             nums.each do 
          |n|
              result.delete_at(result.index(n)) 
          if result.index(n)
             end
             result
           end
          end
          #從集合選元素
          one=amb.choose(*array)
          two
          =amb.choose(*(array.delete(one)))
          three
          =amb.choose(*(array.delete(one,two)))
          four
          =amb.choose(*(array.delete(one,two,three)))
          five
          =amb.choose(*(array.delete(one,two,three,four)))
          six
          =amb.choose(*(array.delete(one,two,three,four,five)))

          #條件1:第二個位置不能是7
          amb.require(two!=7)
          #條件2:6跟8不能一起出現(xiàn)
          def six_eight_not_join(a,b)
             
          "#{a}#"!="68"&&"#{a}#"!="86"
          end
          amb.require(six_eight_not_join(one,two))
          amb.require(six_eight_not_join(two,three))
          amb.require(six_eight_not_join(three,four))
          amb.require(six_eight_not_join(four,five))
          amb.require(six_eight_not_join(five,six))

          #條件3:不重復(fù),利用全局hash判斷
          def distinct?(one,two,three,four,five,six)
            
          if $hash["#{one},#{two},#{three},#{four},#{five},#{six}"].nil?
               $hash[
          "#{one},#{two},#{three},#{four},#{five},#{six}"]=1 #記錄
               true
            
          else
               false
            end
          end
          amb.require(distinct?(one,two,three,four,five,six))
          puts 
          "#{one},#{two},#{three},#{four},#{five},#{six}"
          amb.failure


             三個條件的滿足通過amb.require來設(shè)置,這里安排的只是一種順序,可以根據(jù)實際測試結(jié)果來安排這些條件的順序以最大程度地提高效率。代碼注釋很清楚了,我就不多嘴了。Ruby amb的實現(xiàn)可以看這里。什么是amb可以看這個。



          評論

          # re: amb解決排列組合問題  回復(fù)  更多評論   

          2009-10-19 17:48 by 淘寶皇冠大全
          謝謝分享!

          # re: amb解決排列組合問題  回復(fù)  更多評論   

          2009-10-20 03:18 by 美容
          amb解決排列組合問題 good
          主站蜘蛛池模板: 雷山县| 万州区| 思南县| 卫辉市| 穆棱市| 仁寿县| 曲沃县| 上饶县| 阳原县| 京山县| 夏河县| 巴林右旗| 炎陵县| 普安县| 万盛区| 江油市| 竹溪县| 甘洛县| 惠来县| 嘉祥县| 东兴市| 孙吴县| 房产| 资阳市| 鄱阳县| 南郑县| 株洲市| 磴口县| 长葛市| 顺平县| 保康县| 灵寿县| 枣阳市| 西乌| 许昌县| 犍为县| 改则县| 涿州市| 嘉祥县| 永川市| 潮安县|