Reputation: 863
I'm creating a checkers game and I need a procedure that randomly selects a pair from a list of pairs.
Upvotes: 0
Views: 2562
Reputation: 466
A bit more succinctly solution:
(define (select-random my-lst)
(list-ref
my-lst
(random (length my-lst)))
)
> (select-random '(1 2 3 4))
3
Upvotes: -1
Reputation: 61
I know its been a while since this question was asked but maybe its useful for someone somewhere sometime. You could also do:
(car ;; "car" picks the first element or the "head" of a list
(shuffle ;; well... shuffles
(yourList)))
Upvotes: 6
Reputation: 45747
(define select-random
(lambda (ls)
(let ((len (length ls))) ;; find out how long the list is
(list-ref ls (random len))))) ;; pick one from 0 to the end
Upvotes: 4