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