August 19, 2024

P23 - Extract a given number of randomly selected elements from a list

The selected items shall be returned in a list.

Example:* (rnd-select '(a b c d e f g h) 3)(E D A)

Hint: Use the built-in random number generator and the result of problem P20.

lisp

(load "p03.lisp")
(load "p20.lisp")


;;; Function that receives a list of options and a number of ;;;
;;; elements to be drawn, returning a list with ;;;
;;; the elements that are drawn. If the number of ;;;
;;; elements requested are greater than the number of elements ;;;
;;; behavior is indefinite.                          ;;

(defun rnd-select (org-list num &optional (selected 0))
    (if (eql in a selected)
        nil
        (let ((rand-pos (+ (random (length org-list)) 1))
           (cons (element-at org-list rand-pos) (rnd-select (remove-at org-list rand-pos) num (+ selected 1)))))
Be first to comment
Leave a reply