; How do I compute the sum of N random numbers? ;;; Procedure: ;;; sum-n-random ;;; Parameters: ;;; n, an integer (the number of random integers) ;;; low, the lower bound of the range of random integer ;;; high, the upper bound of the range of random integer ;;; Purpose: ;;; To compute the sum of n random integers in the range ;;; [low..high] (inclusive). ;;; Produces: ;;; sum, an integer ;;; Preconditions: ;;; low <= high ;;; n is not negative ;;; Postconditions: ;;; sum = r1 + r2 + ... + rn ;;; where ri in [low..high] for all i between 1 and n. ;;; sum is hard to predict. (In particular, it will be different ;;; for different calls of sum-n-random and the results of ;;; subsequent calls will not follow an easy-to-detect pattern.) ;;; sum follows the appropriate statistical distribution for a ;;; sum in which each ri is also difficult to predict. (define sum-n-random (lambda (n low high) (if (= n 0) 0 (+ (ranged-random low high) (sum-n-random (- n 1) low high))))) (define sum-n-random-wrong (lambda (n low high) (ranged-random (* n low) (* n high)))) ; Side note: (random x) returns a hard-to-predict integer in the ; range [0..x). ; How do you produce a number in the range [low..high] ; (+ low (random (- high low))) (define ranged-random (lambda (low high) (+ low (random (+ 1(- high low)))))) (define random-list (lambda (length low high) (if (= length 0) null (cons (ranged-random low high) (random-list (- length 1) low high))))) (define random-sums (lambda (length n low high) (let kernel ((to-go length)) (if (= to-go 0) null (cons (sum-n-random n low high) (kernel (- to-go 1)))))))