Get numbers for the lottery

前端 未结 3 1742
悲&欢浪女
悲&欢浪女 2021-01-15 01:45

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

  • a list
  • of
相关标签:
3条回答
  • 2021-01-15 02:29
    (defun lotto ()
      (labels ((lot (acc)  
                 (if (= 6 (length acc)) 
                     acc 
                    (lot (adjoin (1+ (random 49)) acc)))))
        (sort (lot nil) #'<)))
    
    0 讨论(0)
  • 2021-01-15 02:34

    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)
    
    0 讨论(0)
  • 2021-01-15 02:44

    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.

    0 讨论(0)
提交回复
热议问题