From c6741bcc31967040aa57c23b9aa79dc05e61d14d Mon Sep 17 00:00:00 2001 From: Karsten Schmidt Date: Mon, 19 Apr 2021 08:41:07 +0100 Subject: [PATCH] refactor(random): minor updates weightedRandom() --- packages/random/src/unique-indices.ts | 2 +- packages/random/src/weighted-random.ts | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/random/src/unique-indices.ts b/packages/random/src/unique-indices.ts index 59572586d3..a640895d85 100644 --- a/packages/random/src/unique-indices.ts +++ b/packages/random/src/unique-indices.ts @@ -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`); diff --git a/packages/random/src/weighted-random.ts b/packages/random/src/weighted-random.ts index 7143c17773..ae1ba20ca5 100644 --- a/packages/random/src/weighted-random.ts +++ b/packages/random/src/weighted-random.ts @@ -28,18 +28,18 @@ export const weightedRandom = ( 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 undefined;