Skip to content

Commit

Permalink
refactor(random): minor updates weightedRandom()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Apr 19, 2021
1 parent 472489f commit c6741bc
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
2 changes: 1 addition & 1 deletion packages/random/src/unique-indices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const uniqueIndices = (
k: number,
max: number,
existing?: number[],
maxTrials?: number,
maxTrials = max,
rnd: IRandom = SYSTEM
) => {
assert(k >= 0 && k <= max, `k must be in [0, ${max}] interval`);
Expand Down
12 changes: 6 additions & 6 deletions packages/random/src/weighted-random.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,18 @@ export const weightedRandom = <T>(
assert(n > 0, "no choices given");
const opts = weights
? choices
.map((x, i) => <[T, number]>[x, weights[i]])
.sort((a, b) => b[1] - a[1])
: choices.map((x) => <[T, number]>[x, 1]);
const total = opts.reduce((acc, o) => acc + o[1], 0);
.map((x, i) => <[number, T]>[weights[i], x])
.sort((a, b) => b[0] - a[0])
: choices.map((x) => <[number, T]>[1, x]);
const total = opts.reduce((acc, o) => acc + o[0], 0);
total <= 0 && console.warn("total weights <= 0");
return () => {
const r = rnd.float(total);
let sum = total;
for (let i = 0; i < n; i++) {
sum -= opts[i][1];
sum -= opts[i][0];
if (sum <= r) {
return opts[i][0];
return opts[i][1];
}
}
return <never>undefined;
Expand Down

0 comments on commit c6741bc

Please sign in to comment.