Skip to content

Instantly share code, notes, and snippets.

@chuangzhu
Last active July 14, 2018 14:17
Show Gist options
  • Save chuangzhu/157c0a979bd84d6c953d1d41a92385e2 to your computer and use it in GitHub Desktop.
Save chuangzhu/157c0a979bd84d6c953d1d41a92385e2 to your computer and use it in GitHub Desktop.
Hypergeometric Distribution Sequence
'use strict'
function fact(n) {
if (n > 1) return n * fact(n - 1)
else return 1
}
function combination(n, m) {
/* C(n, m) = n * (n-1) * ... * (n-m+1) / m! */
if (!(n >= m)) console.error(new Error("m must be smaller than n"))
var res = 1
for (var i = 0; i < m; i++) {
res *= n - i
}
res /= fact(m)
return res
}
/**
* @param N
* the number of all products
* @param M
* the number of shobby products
* @param n
* the number of products you draw
*/
function hyperGeoDistriSeq(N, M, n) {
/* P(X=k) = C(M, k) * C(N-M, n-k) / C(n, N) */
var res = {}
const C = combination
var denominator = C(N, n)
for (var k = 0; k <= Math.min(n, M); k++) {
res[k] = C(M, k) * C(N-M, n-k) / denominator
}
return res
}
/**
* DEMO
*/
(function () {
const H = hyperGeoDistriSeq
const rl = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
rl.question('How many products are there? ', (N) => {
rl.question('How many products are defective? ', (M) => {
rl.question('How many products will you choose? ', (n) => {
const distri = H(N, M, n)
var X = ''
var P = ''
for (var i in distri) {
var x = i.toString()
var p = distri[i].toString()
if (x.length > p.length) {
p += ' '.repeat(x.length - p.length)
} else if (x.length < p.length) {
x += ' '.repeat(p.length - x.length)
}
X += ' ' + x + ' |'
P += ' ' + p + ' |'
}
console.log(`
X ~ H(N=${N}, M=${M}, n=${n})
| X |${X}
${'-'.repeat(`| X |${X}`.length)}
| P |${P}`)
rl.close();
})
})
})
})()
@chuangzhu
Copy link
Author

2018-07-01-065

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment