lisp - Get numbers for the lottery -


as part of learning lisp i'm trying write function helps me fill out lottery ticket. want function return

  • a list
  • of 6 numbers,
  • where each number between 1 , 49,
  • without duplicate numbers,
  • and being list ordered in ascending way.

so far, i'm done 4 of 5 requirements. current code:

(defun lottery ()   (sort (loop repeat 6 collect (1+ (random 49))) #'<)) 

when run function such as:

(lottery) ;; => (3 10 23 29 41 43) 

basically, everything's fine - except have same number twice within list. , here starts puzzling. problem i'm not sure on how solve in lisp way. there multiple options can think of:

  • run remove-duplicates on result, use length check whether list has less 6 elements, , if so, run lottery second time, append first result, use subseqto first 6 elements, , repeat. works, not elegant, involves sorting & co. multiple times.
  • start empty list, create single random number using (1+ (random 49)), , call pushnew. call lottery recursively list until length returns six. approach way more, i'm still not convinced, way i'd need 2 functions: outer one, lottery, , inner one, called recursively , handles list parameter.
  • start hash-table, use numbers 1 49 keys, , set keys' value nil. then, inside loop, random number between 1 , 49, , change value of appropriate key t. return once 6 elements of hash-table have t value. imho worst approach far, wastes memory quite lot , doesn't scale well.

what think of options, , there other ways of implementing this? how advanced lisp developer solve this?

any hints?

create list of numbers 1 49, shuffle, take 6, sort.

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

addition original poster:

just show final implementation, i'm adding here:

(defun shuffle (list)   (let ((len (length list)))     (loop repeat len               (rotatef           (nth (random len) list)           (nth (random len) list))               (return list))))  (defun lottery ()   (sort (subseq (shuffle (loop 1 49 collect i)) 0 6) #'<))  (lottery) ;; => (5 6 17 21 35 37) 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -