1
0
mirror of https://github.com/psychopy/psychojs.git synced 2025-05-10 10:40:54 +00:00

Remove value from weights too if replace is false

This commit is contained in:
Todd Parsons 2023-08-31 12:43:28 +01:00
parent bfbcf72c56
commit 4cacf0c71d

View File

@ -434,6 +434,12 @@ export function shuffle(array, randomNumberGenerator = undefined)
*/
export function randchoice(a, size = 1, replace = true, p = null, randomNumberGenerator = null)
{
let weights = p
if (weights === null) {
// if no weights given, use uniform
weights = Array.from({length: a.length}, () => 1/a.length)
}
if (!Number.isInteger(size) | size < 1) {
// raise error if given an invalid size
throw {
@ -461,7 +467,10 @@ export function randchoice(a, size = 1, replace = true, p = null, randomNumberGe
values.push(val)
// if replace is false, remove value from copy of array
if (!replace) {
tempArray.pop(val)
let j = tempArray.indexOf(val)
tempArray.pop(tempArray[j])
weights.pop(weights[j])
}
}
return values
@ -473,12 +482,6 @@ export function randchoice(a, size = 1, replace = true, p = null, randomNumberGe
randomNumberGenerator = Math.random;
}
let weights = p
if (weights === null) {
// if no weights given, use uniform
weights = Array.from({length: a.length}, () => 1/a.length)
}
// normalize and accumulate weights
let total = weights.reduce((x, y) => x + y, 0)
let accum = 0