Skip to content

Instantly share code, notes, and snippets.

@goloroden
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goloroden/97726ae346e08f3ada43 to your computer and use it in GitHub Desktop.
Save goloroden/97726ae346e08f3ada43 to your computer and use it in GitHub Desktop.
My first 'real' Lisp program…
(defun lottery ()
(flet ((shuffle (list)
(let ((len (length list)))
(loop repeat len
do
(rotatef
(nth (random len) list)
(nth (random len) list))
finally
(return list)))))
(sort (subseq (shuffle (loop for i from 1 to 49 collect i)) 0 6) #'<)))
(lottery)
;; => (5 6 17 21 35 37)
@lispm
Copy link

lispm commented Jun 9, 2014

;; here is a version with a better shuffle function. Note that the shuffle
;; function is written in a functional Lisp style. You need to read it from
;; inside to outside.
;; it uses a vector where the elements get a random double float attached.
;; The vector gets sorted by the random double floats.

;; the vector-iota function is another utility function

;; the 'domain' level LOTTERY function then is just a composition of the utility functions

(defun shuffle (v)
  (map-into v
            #'car
            (sort (map-into (make-array (length v))
                            (lambda (e)
                              (cons e (random 1.0d0)))
                            v)
                  #'<
                  :key #'cdr)))

(defun vector-iota (start end)
  "returns a vector with elements from start to end"
  (check-type start fixnum)
  (check-type end fixnum)
  (assert (>= end start) (start end))
  (let ((v (make-array (- end start -1))))
    (loop for i from start upto end do (setf (aref v (- i start)) i))
    v))

(defun lottery (&aux
                (start 1)
                (end 49))
  (sort (subseq (shuffle (vector-iota start end))
                0 6)
        #'<))

@frankgerhardt
Copy link

; Clojure
(take 6 (distinct (repeatedly #(inc (rand-int 49)))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment