gn66
gn66

Reputation: 863

How do I write a procedure that randomly selects a pair from a list?

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

Answers (3)

MariaMsu
MariaMsu

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

nescio3d
nescio3d

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

erjiang
erjiang

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

Related Questions