Random, non-repeating picking of m elements from a list (in Lisp)


(defun random-pick-from-list (m lst)
  (let ((lng-lst (length lst)))
    (if (or (<= m 0) (> m lng-lst))
      nil
      (loop 
        with el 
        until (= (length rand-lst) m)
        when (not (find 
                    (setf el (nth (random lng-lst) lst)) 
                    rand-lst))
          append (list el) into rand-lst 
        finally (return rand-lst)))))

It returns a list of m random elements from the list lst.

The elements are different (no repetitions).

Example:


(setf *p* '((a1 b1) (a2 b2) (a3 b3) (a4 b4) (a5 b5)))

(random-pick-from-list 2 *p*)

returns


((A5 B5) (A3 B3))
Advertisements
Published in: on 27/02/2013 at 10:40  Leave a Comment  

The URI to TrackBack this entry is: https://burubaxair.wordpress.com/2013/02/27/random-non-repeating-picking-of-m-elements-from-a-list-in-lisp/trackback/

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: