As part of learning Lisp I\'m currently trying to write a function that helps me fill out my lottery ticket. I want that function to return
(defun lotto ()
(labels ((lot (acc)
(if (= 6 (length acc))
acc
(lot (adjoin (1+ (random 49)) acc)))))
(sort (lot nil) #'<)))
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)
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)
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.