我有乐透的密码它工作得很好,但我希望随机生成数字,而不是作为参数传递给函数。
我认为(cons(+1(random 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...")))

最佳答案

您应该实现一个新函数draw-lottery并将结果传递给play-lotto
我会像费舍尔·耶茨那样洗牌。

(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)))

关于lisp - 彩票代码更正,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29526805/

10-10 13:49