Jump to content

Featured Replies

Posted

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

 

Thanks. For completeness, below is a link to another rnd-pick variant with probability support. 

 

Best,

Torsten

 

Create an account or sign in to comment


Copyright © 2014-2025 Opusmodus™ Ltd. All rights reserved.
Product features, specifications, system requirements and availability are subject to change without notice.
Opusmodus, the Opusmodus logo, and other Opusmodus trademarks are either registered trademarks or trademarks of Opusmodus Ltd.
All other trademarks contained herein are the property of their respective owners.

Powered by Invision Community

Important Information

Terms of Use Privacy Policy