Skip to content

Commit

Permalink
refactor(random): update weightedRandom
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Nov 22, 2019
1 parent 18a4380 commit d609182
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions packages/random/src/weighted-random.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { assert } from "@thi.ng/api";
import { IRandom } from "./api";
import { SYSTEM } from "./system";

Expand All @@ -17,29 +18,26 @@ export const weightedRandom = <T>(
weights?: ArrayLike<number>,
rnd: IRandom = SYSTEM
) => {
const n = choices.length;
assert(n > 0, "no choices given");
const opts = choices
.map(
weights
? (x, i) => <[T, number]>[x, weights[i]]
: (x) => <[T, number]>[x, 1]
)
.sort((a, b) => b[1] - a[1]);
const n = choices.length;
let total = 0,
i: number,
r: number,
sum: number;
for (i = 0; i < n; i++) {
total += opts[i][1];
}
const total = opts.reduce((acc, o) => acc + o[1], 0);
assert(total > 0, "no choices given");
return () => {
r = rnd.float(total);
sum = total;
for (i = 0; i < n; i++) {
const r = rnd.float(total);
let sum = total;
for (let i = 0; i < n; i++) {
sum -= opts[i][1];
if (sum <= r) {
return opts[i][0];
}
}
return <never>undefined;
};
};

0 comments on commit d609182

Please sign in to comment.