2015-06-12.scm 808 B

12345678910111213141516171819202122232425262728293031323334353637
  1. ;; Random total
  2. ;; Generate k random positive integers that add up to a total n
  3. (import (scheme base)
  4. (scheme write)
  5. (srfi 27)
  6. (srfi 95))
  7. (define (rand-to-sum k n)
  8. (if (or (<= k 0)
  9. (<= n 0)
  10. (> k n))
  11. (error "rand-to-sum" "Bad parameters"))
  12. (let loop ((i 1)
  13. (total 0)
  14. (out-list '()))
  15. (if (< i k)
  16. (let ((next-num (+ 1 (random-integer (- (- n total) (- k i))))))
  17. (loop (+ i 1)
  18. (+ total next-num)
  19. (cons next-num out-list)))
  20. (cons (- n total) out-list))))
  21. (define (disp-info l)
  22. (display l)
  23. (newline)
  24. (display (length l))
  25. (newline)
  26. (display (apply + l))
  27. (newline))
  28. (random-source-randomize! default-random-source)
  29. (disp-info (sort (rand-to-sum 5 1000)))