CMPS240, Spring 2013, Section 01: Lisp Gold-Coin Silver Coin Problem Simulation

(defun seq (a b) (If (<= a b) (cons a (seq (+ 1 a ) b))))

(defun trial ()
    (let (b1 b2 b3 x sum bag)
        (setf b1 (list 0 0))
        (setf b2 b1 b3 b1)
;gold coins

    (setf x (+ 1 (random 3)))
    (if (= x 1)
        (setf b1 (list (1+ (first b1)) (second b1))))

    (if (= x 2)
        (setf b2 (list (1+ (first b2)) (second b2))))

    (if (= x 3)
        (setf b3 (list (1+ (first b3)) (second b3))))

    (setf x (+ 1 (random 3)))
    (if (= x 1)
        (setf b1 (list (1+ (first b1)) (second b1))))

    (if (= x 2)
        (setf b2 (list (1+ (first b2)) (second b2))))

    (if (= x 3)
        (setf b3 (list (1+ (first b3)) (second b3))))
    (setf x (+ 1 (random 3)))

    (if (= x 1)
        (setf b1 (list (1+ (first b1)) (second b1))))

    (if (= x 2)
        (setf b2 (list (1+ (first b2)) (second b2))))

    (if (= x 3)
        (setf b3 (list (1+ (first b3)) (second b3))))
;silver coins
    (setf x (+ 1 (random 3)))
    (if (= x 1)
        (setf b1 (list  (first b1) (1+ (second b1)))))

    (if (= x 2)
        (setf b2 (list  (first b2) (1+ (second b2)))))
    (if (= x 3)
        (setf b3 (list  (first b3) (1+ (second b3)))))
    (setf x (+ 1 (random 3)))
    (if (= x 1)
        (setf b1 (list  (first b1) (1+ (second b1)))))

    (if (= x 2)
        (setf b2 (list  (first b2) (1+ (second b2)))))
    (if (= x 3)
        (setf b3 (list  (first b3) (1+ (second b3)))))
    (setf x (+ 1 (random 3)))
    (if (= x 1)
        (setf b1 (list  (first b1) (1+ (second b1)))))

 

 (if (= x 2)
        (setf b2 (list  (first b2) (1+ (second b2)))))
    (if (= x 3)
        (setf b3 (list  (first b3) (1+ (second b3)))))
    (setf x (+ 1 (random 3)))
    (if (= x 1)
        (setf b1 (list  (first b1) (1+ (second b1)))))
    (if (= x 2)
        (setf b2 (list  (first b2) (1+ (second b2)))))
    (if (= x 3)
        (setf b3 (list  (first b3) (1+ (second b3)))))

    ;select a bag with a gold coin.

(setf x (1+ (random 3)))   ;which coin

(setf sum (first b1))

(if  (<= x sum)   (setf bag b1)
     (progn
          (setf sum (+ sum (first b2)))
          (if (<= x sum) (setf bag b2)
                         (setf bag b3))))

(print (list b1 b2 b3 bag x)) (terpri)

;(setf x  (+ 1 (random (+ -1 (first bag) (second bag))))); this line blows up!

;***************************

;fix:

(setf x (+ -1 (first bag) (second bag)))
(if (< x 1) (setf x 99999999)
            (setf x (+ 1 (random x))))

 

(print x) (terpri)
(<= x (- (first bag) 1))


))

(print (count 't (mapcar #'(lambda (x) x (trial)) (seq 1 10000))))
(terpri)