Advertisement
Guest User

Untitled

a guest
Oct 25th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns risk)
  2.  
  3. (defn roll [] (+ 1 (rand-int 6)))
  4.  
  5. (defn fight-round [attackers defenders]
  6.   (assert (and (> attackers 0) (> defenders 0)))
  7.   (let [a (min attackers 3)
  8.         d (min defenders 2)
  9.         attack-rolls (sort > (take a (repeatedly roll)))
  10.         defense-rolls (sort > (take d (repeatedly roll)))
  11.         results (map - defense-rolls attack-rolls)]
  12.     {:attackers (- attackers (count (filter #(>= % 0) results)))
  13.      :defenders (- defenders (count (filter neg? results)))}))
  14.  
  15. (defn fight-battle [attackers defenders]
  16.   (assert (and (> attackers 1) (> defenders 0)))
  17.   (loop [a (dec attackers) d defenders]
  18.     (cond (<= a 0) {:attackers a :defenders d :result :defenders-win}
  19.           (<= d 0) {:attackers a :defenders d :result :attackers-win}
  20.           :else (let [{an :attackers dn :defenders} (fight-round a d)]
  21.                   (recur an dn)))))
  22.  
  23. (defn simulate
  24.   "return an infinite series of battle results"
  25.   [attackers defenders]
  26.   (repeatedly #(fight-battle attackers defenders)))
  27.  
  28. (defn compute-stats
  29.   "compute win % and avg remaining soldiers given a list of results"
  30.   [results]
  31.   (let [win-counts (frequencies (map :result results))
  32.         remaining-attackers (reduce + (map :attackers results))
  33.         remaining-defenders (reduce + (map :defenders results))]
  34.     {:win-ratio (/ (:attackers-win win-counts) (count results))
  35.      :avg-attackers (/ remaining-attackers (:attackers-win win-counts))}))
  36.  
  37. (defn main []
  38.   (let [results (take 10000 (simulate 9 9))
  39.         stats (compute-stats results)]
  40.     (printf "attackers win %.2f%% of the time"
  41.             (double (* 100 (:win-ratio stats))))
  42.     (printf " with %.4f soldiers remaining on average"
  43.             (double (:avg-attackers stats)))))
  44.  
  45. ======================================
  46. Output:
  47. risk> (main)
  48. attackers win 0.47% of the time with 3.9868 soldiers remaining on average
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement