data_pi
data_pi

Reputation: 821

Racket - Picking a random element from a list

I'm not sure how to make this code work, its so late here that I think my brain has stopped functioning, anyone care to give me a hand?

The code so far:

(define maze-size 15)
(define-struct Cell (x y))

; adjacents : Cell -> list-of-Cells
; Produce a list of the four Cells above, below, left, and right of 'cell'.

(define(adjacents cell x y)
(list
(make-Cell x (+ y 1))
(make-Cell x (- y 1))
(make-Cell (- x 1) y)
(make-Cell (+ x 1) y)))

Here is where I am getting stumped, how do I fix this? Note: The code below does not work.

; random-adjacent : list-of-Cells -> Cell
; Produce a random Cell adjacent to a random Cell from the non-empty list'cells'.

(define (random-adjacent cells)
(random (adjacents cell)))

This is what it should behave like:

(check-expect (member? (random-adjacent (list (make-Cell 123 104)))
                   (list (make-Cell 123 105)
                         (make-Cell 123 103)
                         (make-Cell 122 104)
                         (make-Cell 124 104)))
          #true)

Upvotes: 1

Views: 1380

Answers (1)

uselpa
uselpa

Reputation: 18937

This passes your tests:

(define-struct Cell (x y))

(define (adjacents cell)
  (list
   (make-Cell (Cell-x cell) (+ (Cell-y cell) 1))
   (make-Cell (Cell-x cell) (- (Cell-y cell) 1))
   (make-Cell (- (Cell-x cell) 1) (Cell-y cell))
   (make-Cell (+ (Cell-x cell) 1) (Cell-y cell))))

(define (random-adjacent cell)
  (let ((neighbors (adjacents cell)))
    (list-ref neighbors (random (length neighbors)))))

(check-expect (member? (random-adjacent (make-Cell 123 104))
                       (list (make-Cell 123 105)
                             (make-Cell 123 103)
                             (make-Cell 122 104)
                             (make-Cell 124 104)))
              #true)

Upvotes: 2

Related Questions