如何在Lisp中编写乐透编码,用户在1-45之间随机生成6个数字(非重复),然后输入他们自己选择的乐透编号以查看它们是否匹配,然后告诉他们是否&# 39;赢了还是不赢?
(defun shuffle (list)
(let ((len (length list)))
(loop repeat len
do (rotatef (nth (random len) list)
(nth (random len) list))
finally (return list))))
(defun lottery ()
(sort (subseq (shuffle (loop for i from 1 to 49 collect i))
0 6)
#'<))
(lottery)
(该代码实际上取自此问题的其他作者:Get numbers for the lottery)
这会输出我需要的随机数,但是我在输入6个数字并将它们与这些数字进行比较时会遇到很多麻烦,以确定它们是否已经赢得了39;。
答案 0 :(得分:2)
让我们从获得n
非重复随机数开始。
(defun get-n-rand (n)
(loop :for i = (adjoin (1+ (random 44)) i)
:when (= (length i) n) :return i))
现在,如果我们想要其中6个就足够简单来编写(get-n-rand 6)
接下来,我们要检查是否可以在另一个列表中找到一个列表的每个成员。
(defun check-user-guess (guess-list actual-list)
(equal (sort guess-list #'<) (sort actual-list #'<)))
希望这涵盖了核心逻辑。输入我将暂时离开,因为它在另一个答案中有所涉及。
答案 1 :(得分:1)
如果你的问题是输入,那么这应该是一个(不安全的)解决方案:
(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 #'<) (lottery))
(princ "You won!")
(princ "You lost...")))