combination-and-permutation
Version:
Combination or Permutation computation
59 lines • 1.52 kB
JavaScript
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;
}
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);
}
rates[m] = rates[m - 1] + now;
total += now;
}
const nw = Math.floor(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;
}
//# sourceMappingURL=index.js.map