John C
John C

Reputation: 39

Building a random list

I am trying to write a function that takes in the length of a list and a maximum number value and returns a list that is the length given with numbers between 1 and the given max randomly.

so far I have

(define (randomlist n max)
(cond
  [(= n 0)empty]
  [else
      (cons (build-list n (random 1 max))
            (randomlist max (- n 1)))]))

I get an error when I run this and was wondering if anybody could help me out.

Upvotes: 1

Views: 1793

Answers (2)

rnso
rnso

Reputation: 24623

One can also use for/list to combine loop and list formation:

(define (randomlist n mx)
  (for/list ((i n))
    (add1 (random mx))))

Testing:

(randomlist 5 10)

Output:

'(5 9 10 4 7)  

(random numbers, hence output is very likely to be different each time).

Upvotes: 4

Óscar López
Óscar López

Reputation: 236140

There are several bugs in your code:

  • It's a bad idea to call a parameter max, that clashes with a built-in procedure. So I renamed it to mx.
  • There's absolutely no reason to use build-list, that's not how we build an output list, just cons one element with the rest.
  • random receives zero or one parameters, not two. The single-parameter version returns an integer in the range 0..n-1, hence we have to add 1 to the result to be in the range 1..n.
  • You switched the order of the parameters when recursively calling randomlist.

This should take care of the problems:

(define (randomlist n mx)
  (cond
    [(= n 0) empty]
    [else
     (cons (+ 1 (random mx))
           (randomlist (- n 1) mx))]))

It works as expected:

(randomlist 5 10)
=> '(10 7 1 4 8) ; results will vary, obviously

Upvotes: 2

Related Questions