gpt4 book ai didi

lisp - 彩票代码更正

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:50 25 4
gpt4 key购买 nike

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

我在想包含 (cons (+1 (random 50)) list) 可能行得通,但我不确定如何正确实现!

(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

我会将其作为部分 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)))

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com