views:

203

answers:

3

Hello Under scheme I want to generate a vector of random numbers, I have tried this like this:

(make-vector 10 (random 100))

and the output for this is such:

#(44 44 44 44 44 44 44 44 44 44)

so it seems like it uses the same seed for the generated items, how can I overcome this problem of generating n amount of randomly generated number sequence.

Cheers

+1  A: 

You need to call random 100 once for each element of the vector.

Peter
so make-vector is pretty useless for me as far as I see.
Hellnar
@Hellnar: no, you still need make-vector to make a vector in the first place, and then you set each element
newacct
+2  A: 

If you are using PLT Scheme you can use build-vector:

(build-vector 100 (lambda (_) (random 100)))

If you are using one of the standardized versions (R5RS, R6RS etc.) you can define build-vector yourself, for example like this:

(define (build-vector n f)
  (let ((v (make-vector n)))
    (do ((i 0 (+ i 1))) ((> i 9) v)
      (vector-set! v i (f i)))))
Jonas
thanks alot, may I ask you the meaning of "lambda (_)"? thanks
Hellnar
I just put an underscore as variable name since I never used it in the function body.
Jonas
+1  A: 

Another way to do it:

  (define (random-vector count seed)
    (let loop ((vec '(vector)) (i count))
      (cond ((> i 0)
          (loop (cons (random seed) vec) (sub1 i)))
         (else (eval (reverse vec))))))

May not be the best solution, but shows how to write and evaluate a Scheme program at runtime. Maybe useful for new Schemers.

Some example usages:

> (random-vector 10 100)
#10(53 57 47 34 88 32 70 66 92 56)

> (random-vector 100 500)
#100(42 1 250 396 63 120 185 397 251 88 497 271 246 327 91 108 240 306 445 180 292 55 497 67 445 300 279 229 342 122 498 10 253 248 44 133 450 55 112 13 309 255 101 456 272 7 239 113 394 453 89 343 386 471 92 44 61 239 382 313 78 22 376 466 24 97 286 343 237 220 458 153 131 217 390 94 53 461 237 22 327 196 460 436 311 418 41 124 79 24 37 388 344 176 314 432 26 341 303 218)
Vijay Mathew