4clojure第135个问题:中缀计算器

(ns for-clojure.problem135)

(defn infix-calculator
  "前缀计算机,从左到右执行,不论优先级"
  [& xs]
  (loop [r (first xs)
         xs (rest xs)]
    (if (empty? xs)
      r
      (recur ((first xs) r (second xs)) (nthrest xs 2)))))

(= 72 (infix-calculator 20 / 2 + 2 + 4 + 8 - 6 - 10 * 9))

 
(nthrest xs n)返回序列xs第n个元素后的子序列,所以 (rest (rest xs))等同于(nthrest xs 2)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个用Clojure实现的德州扑克概率计算器的示例代码: ```clojure (def suits ["H" "D" "C" "S"]) (def ranks ["2" "3" "4" "5" "6" "7" "8" "9" "T" "J" "Q" "K" "A"]) (defn new-deck [] (for [suit suits rank ranks] (str rank suit))) (defn shuffle-deck [deck] (shuffle deck)) (defn deal-hand [deck] (take 2 deck)) (defn deal-board [deck] (take 5 (drop 2 deck))) (defn sort-hand [hand] (sort-by #(index-of ranks %) hand)) (defn hand-straight? [hand] (let [sorted-hand (sort-hand hand) straight-ranks (take 5 (iterate inc (index-of ranks (first sorted-hand))))] (= (map #(index-of ranks %) sorted-hand) straight-ranks))) (defn hand-flush? [hand] (let [suit-counts (frequencies (map last hand))] (some #(>= % 5) suit-counts))) (defn hand-straight-flush? [hand] (and (hand-straight? hand) (hand-flush? hand))) (defn hand-four-of-a-kind? [hand] (let [rank-counts (frequencies (map first hand))] (some #(= % 4) rank-counts))) (defn hand-full-house? [hand] (let [rank-counts (frequencies (map first hand))] (and (some #(= % 3) rank-counts) (some #(= % 2) rank-counts)))) (defn hand-three-of-a-kind? [hand] (let [rank-counts (frequencies (map first hand))] (some #(= % 3) rank-counts))) (defn hand-two-pairs? [hand] (let [rank-counts (frequencies (map first hand))] (= (count (filter #(= % 2) rank-counts)) 2))) (defn hand-one-pair? [hand] (let [rank-counts (frequencies (map first hand))] (some #(= % 2) rank-counts))) (defn hand-high-card [hand] (last (sort-hand hand))) (defn hand-type [hand] (cond-> :high-card (hand-straight-flush? hand) (constantly :straight-flush) (hand-four-of-a-kind? hand) (constantly :four-of-a-kind) (hand-full-house? hand) (constantly :full-house) (hand-flush? hand) (constantly :flush) (hand-straight? hand) (constantly :straight) (hand-three-of-a-kind? hand) (constantly :three-of-a-kind) (hand-two-pairs? hand) (constantly :two-pairs) (hand-one-pair? hand) (constantly :one-pair))) (defn simulate [n] (let [deck (shuffle-deck (new-deck)) hands (for [i (range n)] (let [hand (deal-hand deck) board (deal-board deck) cards (concat hand board)] (hand-type cards)))] (frequencies hands))) (simulate 100000) ``` 这个程序定义了一些基本函数,比如生成一副牌、洗牌、发牌、牌型判断等,最后通过模拟大量牌局来计算每种牌型的概率。 您可以在此基础上进行修改和扩展,比如增加计算胜率的功能等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值