So i have a doubt , i have some points pre-defined ex:
Code: Select all
(defvar a '(23 20))
(defvar b '(10 30))
(defvar c '(0 45))
(defvar d '(43 0))
Code: Select all
(defvar a '(23 20))
(defvar b '(10 30))
(defvar c '(0 45))
(defvar d '(43 0))
Code: Select all
(defparameter *lst* (list a b c d)) ; list of the elements
(setf *lst*
(sort *lst*
(lambda (&rest lst)
(< 0.5 (random 1.0)))))
sylwester wrote:You can randomize it with sort:
Code: Select all
(defparameter *lst* (list a b c d)) ; list of the elements (setf *lst* (sort *lst* (lambda (&rest lst) (< 0.5 (random 1.0)))))
It won't work with every sorting algorithm. With something like quicksort, you're partitioning the sequence recursively and rearranging each partition around some pivot element—with a random predicate, the pivot is irrelevant, of course. So it's like flipping a coin to decide whether to swap around a given element within the partition. Personally, I'd use a Fisher-Yates shuffle, which is like playing Bingo:Domus123 wrote:That code seems work,but how exactly that work?sylwester wrote:You can randomize it with sort:
Code: Select all
(defparameter *lst* (list a b c d)) ; list of the elements (setf *lst* (sort *lst* (lambda (&rest lst) (< 0.5 (random 1.0)))))
Code: Select all
(defun shuffle (list)
(loop for tail on list
for n downfrom (list-length list) above 1
do (rotatef (car tail) (nth (random n) tail))
finally (return list)))
Since that's exactly what is wanted here using RANDOM with SORT is fine.This is guaranteed even if the predicate does not really consistently represent a total order (in which case the elements will be scrambled in some unpredictable way, but no element will be lost)