Jump to content

flexible rnd-pick function


Recommended Posts

a "rnd-pick" that works with different "input-formats"... so it's flexible to use... for many (not all) input-cases

 

;;; subfunction

(defun weighted-random (list)
  (loop for item in list
    with rand-num = (random (loop for x in list sum (second x)))
    for add = (second item) then (+ add (second item))
    when (< rand-num add) return (first item)))

                    
;;; mainfunction

(defun rnd-pick* (alist)
  (if (and (listp (first alist)) 
           (floatp (second (first alist))))
    (weighted-random alist)
    (rnd-pick alist)))


;;; examples
                    
;;; without weight
(rnd-pick* '(1 2 3 4 5))
(rnd-pick* '((1 2 3 4) (3 4 5 7 3) (75 392 2)))

;;; with weight
(rnd-pick* '((2 0.2) (3 0.4) (4 0.2)))
(rnd-pick* '(((2 3 4 5) 0.2) ((8 796 5) 0.4)))
(rnd-pick* '(((1 3) 0.2) (3 0.3)))

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

Terms of Use Privacy Policy