彩票代码更正

时间:2015-04-08 23:00:48

标签: lisp common-lisp

我有一个乐透的代码。它工作正常,但我希望随机生成数字而不是作为参数传递给函数。

我在考虑包含(cons(+1(随机50))列表)可能有效,但我不确定如何正确实现这一点!

(defun play-lotto (&aux list)
  (dotimes (i 6)
    (loop
     (princ "Write a Integer between 0 and 50: ")
     (let ((number (read)))
       (if (and (integerp number) (< 0 number 50))
           (if (member number list)
               (progn
                 (princ "You can only choose a number once")
                 (terpri))
             (progn
               (push number list)
               (return)))
         (progn
           (princ "Not a Integer between 0 and 50")
           (terpri))))))
  (if (equal (sort list #'<)
             (sort lottery #'<))
      (princ "You won!")
    (princ "You lost...")))

1 个答案:

答案 0 :(得分:0)

您应该实现新功能draw-lottery并将结果传递给play-lotto

我作为部分Fisher-Yates洗牌来做。

(defun iota-vector (end &key (start 0) &aux (length (- end start)))
  "Creates a vector with all numbers from START \(inclusive) to END
\(exclusive).  END must be greater than or equal to START."
  (assert (not (minusp length)))
  (let ((i start))
    (map-into (make-array length)
              (lambda () (prog1 i (incf i))))))

(defun draw-lottery ()
  "Draws six random numbers from 1 to 49 \(inclusive) without replacement and
returns them as a sorted list."
  (let ((urn (iota-vector 50 :start 1)))
    (dotimes (i 6)
      (rotatef (aref urn i)
               (aref urn (+ i (random (- 49 i))))))
    (coerce (sort (subseq urn 0 6) #'<) 'list)))
相关问题