Skip to content

Commit 0615f3f

Browse files
committed
pb 16
1 parent 15aa186 commit 0615f3f

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,3 +230,16 @@ Given a column number, return its alphabetical column id. For example, given 1,
230230

231231
### Solution
232232
[JS](pb15/answer.js) (9:18)
233+
234+
235+
---
236+
237+
## 16
238+
> This problem was asked by Triplebyte.
239+
240+
You are given n numbers as well as n probabilities that sum up to 1. Write a function to generate one of the numbers with its corresponding probability.
241+
For example, given the numbers [1, 2, 3, 4] and probabilities [0.1, 0.5, 0.2, 0.2], your function should return 1 10% of the time, 2 50% of the time, and 3 and 4 20% of the time.
242+
You can generate random numbers between 0 and 1 uniformly.
243+
244+
### Solution
245+
[JS](pb16/answer.js) (12.41)

pb16/Problem.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
> This problem was asked by Triplebyte.
2+
3+
You are given n numbers as well as n probabilities that sum up to 1. Write a function to generate one of the numbers with its corresponding probability.
4+
For example, given the numbers [1, 2, 3, 4] and probabilities [0.1, 0.5, 0.2, 0.2], your function should return 1 10% of the time, 2 50% of the time, and 3 and 4 20% of the time.
5+
You can generate random numbers between 0 and 1 uniformly.

pb16/answer.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Time : 12:41
2+
3+
const roll = (arrNum, arrProb) => {
4+
5+
let ret = "";
6+
7+
let rnd = Math.random();
8+
9+
10+
if(arrNum.length === arrProb.length) {
11+
let sumProb = arrProb.reduce((acc, cur) => acc += cur, 0);
12+
let isProbValid = sumProb === 1;
13+
14+
if (isProbValid) {
15+
16+
let fused = arrNum.map((n, idx) => {
17+
return {
18+
val: n,
19+
prob: arrProb[idx]
20+
}
21+
}).sort((a, b) => {
22+
return b.prob - a.prob;
23+
});
24+
25+
fused.reduce((acc, cur) => {
26+
27+
acc += cur.prob;
28+
29+
cur.prob = acc;
30+
31+
return acc;
32+
}, 0);
33+
34+
let match = fused.find(f => f.prob >= rnd);
35+
36+
ret = `Rolled ${rnd}, returning ${match.val}`;
37+
38+
} else {
39+
ret = "Probabilities does not add up to 1 !";
40+
}
41+
} else {
42+
ret = "Arrays are not the same length !";
43+
}
44+
45+
return ret;
46+
};
47+
48+
49+
let num = [1, 2, 3, 4];
50+
let prob = [0.1, 0.5, 0.2, 0.2];
51+
52+
console.log(roll(num, prob));

0 commit comments

Comments
 (0)