Good morning! Here's our prompt for today.
You are given an array of positive integers w
where w[i]
describes the weight of the ith
index.
Implement the function randomPick()
, which randomly picks an index in the range [0, w.length - 1]
(inclusive) and returns it. The probability of picking an element is w[i] / sum(w)
, where i
is the index of the element.

The function
randomPick()
will be calledn
times (wheren
is an integer), with all the results stored in an array and then evaluated. This is to ensure that the function works correctly as the output may be different for different runs due to the randomness factor.
For example, if w = [1, 3]
, then the total weight of the array is 4
. The probability of picking index 0
is 1/4 = 0.25
(25%), and the probability of picking index 1
is 3/4 = 0.75
(75%).
Constraints
1 <= w.length <= 104
1 <= w[i] <= 105
randomPick()
will be called at most104
times.
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
console.log('PASSED: ' + "`randomPick([1, 3, 2])` should return `[" + result + "]`");
var assert = require('assert');
​
function randomPick(w) {
// add your code here
return;
}
​
​
try {
let result = [];
for (let i = 0; i < 5; i++) {
result.push(randomPick([1, 3]));
assert.equal([0, 1].includes(result[i]), true);
}
console.log('PASSED: ' + "`randomPick([1])` should return `[" + result + "]`");
} catch (err) {
console.log(err);
}
​
try {
let result = [];
for (let i = 0; i < 2; i++) {
result.push(randomPick([1]));
assert.equal([0].includes(result[i]), true);
}
console.log('PASSED: ' + "`randomPick([1])` should return `[" + result + "]`");
} catch (err) {
console.log(err);
}
Here's how we would solve this problem...
How do I use this guide?