[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
another stats problem, example solution [stats.el]
From: |
Emanuel Berg |
Subject: |
another stats problem, example solution [stats.el] |
Date: |
Mon, 04 Sep 2023 20:15:54 +0200 |
User-agent: |
Gnus/5.13 (Gnus v5.13) |
Problem:
Return a list of N random numbers.
Every number is at least MIN.
The sum of the numbers is SUM.
Suggested solution, linear to SUM.
;;; -*- lexical-binding: t -*-
;;
;; this file:
;; https://dataswamp.org/~incal/emacs-init/stats.el
(require 'cl-lib)
(defun random-distribution (n min sum)
"Return a list of N random numbers.
Every number is at least MIN.
The sum of the numbers is SUM."
(let ((min-share (* n min)))
(unless (<= min-share sum)
(error "Bogus indata, unsolvable") )
(let ((vals (make-list n min))
(pool (- sum min-share)) )
(cl-loop while (and (< 0 pool)
(cl-decf pool) )
do (cl-incf (nth (random n) vals)) )
vals) ))
(defalias 'rd #'random-distribution)
;; (apply #'+ (rd 10 3 100)) ; 100
;;
;; (rd 10 10 100) ; border case check, but OK
;;
;; (rd 10 20 100) ; Bogus indata, unsolvable
;;
;; example distributions for n = 10, min = 3, and sum = 100:
;; (12 8 8 10 7 6 19 9 7 14)
;; ( 8 12 7 12 9 10 9 9 12 12)
;; (14 6 15 11 9 9 6 8 11 11)
;; ( 8 12 7 9 10 9 10 13 10 12)
;; (12 12 15 6 10 8 6 10 14 7)
;; ( 9 7 10 8 11 10 9 10 13 13)
;; ( 7 13 13 10 13 10 5 13 5 11)
;; (13 8 6 9 13 8 11 7 10 15)
;; ( 7 10 5 6 17 14 8 10 14 9)
;; (11 10 8 9 11 10 14 11 8 8)
(provide 'stats)
--
underground experts united
https://dataswamp.org/~incal
- another stats problem, example solution [stats.el],
Emanuel Berg <=