Get numbers for the lottery

五迷三道 提交于 2019-12-01 11:11:41
dsm

Create a list of all the numbers from 1 to 49, shuffle, take 6, sort.

=> (sort (take 6 (shuffle (range 1 50))))
; (8 14 16 23 34 39)

Addition by original poster:

Just to show the final implementation, I'm adding it here:

(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)
;; => (5 6 17 21 35 37)
(defun lotto ()
  (labels ((lot (acc)  
             (if (= 6 (length acc)) 
                 acc 
                (lot (adjoin (1+ (random 49)) acc)))))
    (sort (lot nil) #'<)))

Using an accumulator fed by recursion:

(defun lottery ()
  (setf grid (loop for i from 1 to 49 collect i))
  (labels ((choose (source num)
    (if (or (null source) (zerop num))
      nil
      (let ((elem (nth (random (length source)) source)))
        (cons elem (choose (remove elem source) (1- num)))))))
    (sort (choose grid 6) #'<)))

The lottery function is first generating a list of numbers put into the grid variable. Then we define an internal choose local function. This function gets one random number in the list it is provided inside the interface and calls itself on the list minus the chosen element. The last step is to sort the resulting list.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!