Skip to content

Instantly share code, notes, and snippets.

@danielfm
Created November 3, 2010 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielfm/661881 to your computer and use it in GitHub Desktop.
Save danielfm/661881 to your computer and use it in GitHub Desktop.
Little Common Lisp program that returns the winners (and each winner's earnings) of a pool. Uses shallow copies to avoid mutation.
;;; Based on this gist: http://gist.github.com/439264
(defstruct bet name amount guess rate)
(defun pool-amount (pool)
(reduce #'+ (mapcar #'bet-amount pool)))
(defun pool-rates (pool)
(let ((sum (pool-amount pool)))
(mapcar (lambda (bet)
(let ((x (copy-bet bet)))
(setf (bet-rate x) (/ (bet-amount x) sum))
x)) pool)))
(defun pool-winners (pool result)
(let ((sum (pool-amount pool))
(winners (loop for bet in pool when (equal (bet-guess bet) result) collect bet)))
(mapcar (lambda (winner)
(let ((x (copy-bet winner)))
(setf (bet-amount x) (* (bet-rate x) sum))
x)) (pool-rates winners))))
;;; Usage
(defvar *pool*
(list
(make-bet :name "Daniel" :amount 2.0 :guess '(2 0)) ;;; Daniel bets $2 on 2x0
(make-bet :name "John" :amount 4.0 :guess '(0 0)) ;;; and so on...
(make-bet :name "Maria" :amount 1.0 :guess '(2 0))))
(pool-winners *pool* '(0 2)) ;;; NIL
(pool-winners *pool* '(0 0)) ;;; (#S(BET :NAME "John" ... :RATE 1.0))
(pool-winners *pool* '(2 0)) ;;; (#S(BET :NAME "Daniel" ... :RATE 0.6666667) #S(BET :NAME "Maria" ... :RATE 0.33333334))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment