UNPKG

combination-and-permutation

Version:

Combination or Permutation computation

65 lines 1.7 kB
import { fixed } from "./fixed.js"; function computeReady(n) { const rates = fixed.get(n); const nw = Math.random() * rates[0]; let chosenCount = 0; for (let m = 1; m <= n; m++) { if (nw < rates[m]) { chosenCount = m; break; } } if (chosenCount == 0) chosenCount = n; const ok = new Set(); while (ok.size < chosenCount) { const index = Math.floor(Math.random() * n); ok.add(index + 1); } const ret = []; for (const s of ok) ret.push(s); return ret.sort((a, b) => a - b); } export function compute(n) { if (fixed.get(n) != null) { return computeReady(n); } let total = 0; const rates = new Array(n + 1); rates[0] = 0; for (let m = 1; m <= n; m++) { let now = 1; for (let j = 0; j < m; j++) { now = now * (n - j); } for (let j = 2; j <= m; j++) { now /= j; } rates[m] = now; total += now; } for (let m = 1; m <= n; m++) { rates[m] = rates[m - 1] + rates[m]; } const nw = Math.random() * total; let chosenCount = 0; for (let m = 1; m <= n; m++) { if (nw < rates[m]) { chosenCount = m; break; } } if (chosenCount == 0) chosenCount = n; const ok = new Set(); while (ok.size < chosenCount) { const index = Math.floor(Math.random() * n); ok.add(index + 1); } const ret = []; for (const s of ok) ret.push(s); return ret.sort((a, b) => a - b); } //# sourceMappingURL=index.js.map