Sign in to follow this  
Followers 0
AM

flexible rnd-pick function

2 posts in this topic

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)))

 

opmo likes this

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0