Skip to content

Commit

Permalink
Allow any array in pickRandom function
Browse files Browse the repository at this point in the history
  • Loading branch information
KonradLinkowski committed Oct 3, 2020
1 parent bc4d94b commit ca05c25
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 11 deletions.
5 changes: 0 additions & 5 deletions src/function/probability/pickRandom.js
@@ -1,6 +1,5 @@
import { factory } from '../../utils/factory'
import { isNumber } from '../../utils/is'
import { arraySize } from '../../utils/array'
import { createRng } from './util/seededRNG'

const name = 'pickRandom'
Expand Down Expand Up @@ -81,10 +80,6 @@ export const createPickRandom = /* #__PURE__ */ factory(name, dependencies, ({ t
weights = weights.valueOf() // get Array
}

if (arraySize(possibles).length > 1) {
throw new Error('Only one dimensional vectors supported')
}

let totalWeights = 0

if (typeof weights !== 'undefined') {
Expand Down
31 changes: 25 additions & 6 deletions test/unit-tests/function/probability/pickRandom.test.js
Expand Up @@ -10,12 +10,6 @@ describe('pickRandom', function () {
assert.strictEqual(typeof math.pickRandom, 'function')
})

it('should throw an error when providing a multi dimensional matrix', function () {
assert.throws(function () {
pickRandom(math.matrix([[1, 2], [3, 4]]))
}, /Only one dimensional vectors supported/)
})

it('should throw an error if the length of the weights does not match the length of the possibles', function () {
const possibles = [11, 22, 33, 44, 55]
const weights = [1, 5, 2, 4]
Expand Down Expand Up @@ -117,6 +111,31 @@ describe('pickRandom', function () {
assert.strictEqual(pickRandom(possibles, weights, number).length, number)
})

it('should pick an array from the given multi dimensional array following an uniform distribution', function () {
const possibles = [[11, 12], [22, 23], [33, 34], [44, 45], [55, 56]]
const picked = []

times(1000, () => picked.push(pickRandom(possibles)))

possibles.forEach(possible => {
const count = filter(picked, val => val === possible).length
assert.strictEqual(math.round(count / picked.length, 1), 0.2)
})
})

it('should pick a value from the given array following an uniform distribution', function () {
// just to be sure that works for any kind of array
const possibles = [[[11], [12]], ['test', 45], 'another test', 10, false]
const picked = []

times(1000, () => picked.push(pickRandom(possibles)))

possibles.forEach(possible => {
const count = filter(picked, val => val === possible).length
assert.strictEqual(math.round(count / picked.length, 1), 0.2)
})
})

it('should pick a value from the given array following an uniform distribution if only possibles are passed', function () {
const possibles = [11, 22, 33, 44, 55]
const picked = []
Expand Down

0 comments on commit ca05c25

Please sign in to comment.