unofficial mirror of emacs-devel@gnu.org 
 help / color / mirror / code / Atom feed
* another stats problem, example solution [stats.el]
@ 2023-09-04 18:15 Emanuel Berg
  2023-09-04 20:08 ` John Haman
  0 siblings, 1 reply; 5+ messages in thread
From: Emanuel Berg @ 2023-09-04 18:15 UTC (permalink / raw)
  To: emacs-devel

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




^ permalink raw reply	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2023-09-06  0:21 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2023-09-04 18:15 another stats problem, example solution [stats.el] Emanuel Berg
2023-09-04 20:08 ` John Haman
2023-09-05  3:42   ` Emanuel Berg
2023-09-05 11:53     ` Philip Kaludercic
2023-09-06  0:21       ` Emanuel Berg

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/emacs.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).