Skip to content

Commit 2d6c385

Browse files
authored
Create 1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls.js
1 parent 0924729 commit 2d6c385

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* @param {number[]} balls
3+
* @return {number}
4+
*/
5+
const getProbability = function (balls) {
6+
const k = balls.length
7+
const halfUsed = balls.reduce((acc, val) => acc + val, 0) / 2
8+
const startArray = new Array(k)
9+
startArray.fill(0)
10+
const perm = function (b1, b2) {
11+
let p1, p2, s1, s2
12+
s1 = b1.reduce((acc, val) => acc + val, 0)
13+
s2 = b2.reduce((acc, val) => acc + val, 0)
14+
const fact = function (n) {
15+
let f = 1
16+
for (let i = 2; i <= n; i++) f *= i
17+
return f
18+
}
19+
p1 = fact(s1)
20+
p2 = fact(s2)
21+
b1.forEach((val) => {
22+
if (val > 1) p1 /= fact(val)
23+
})
24+
b2.forEach((val) => {
25+
if (val > 1) p2 /= fact(val)
26+
})
27+
return p1 * p2
28+
}
29+
30+
const getValidCombos = function (ballsUsed, colorNum = 0) {
31+
let box1Used = ballsUsed.reduce((acc, val) => acc + val, 0)
32+
let matches = { good: 0, total: 0 },
33+
thisColorMax = halfUsed - box1Used
34+
if (colorNum === k - 1) {
35+
if (thisColorMax > balls[colorNum]) return { good: 0, total: 0 }
36+
ballsUsed[colorNum] = thisColorMax
37+
let ballsLeft = []
38+
let colorsUsed = [0, 0]
39+
for (let i = 0; i < k; i++) {
40+
ballsLeft[i] = balls[i] - ballsUsed[i]
41+
if (ballsUsed[i] > 0) colorsUsed[0]++
42+
if (ballsLeft[i] > 0) colorsUsed[1]++
43+
}
44+
let permutations = perm(ballsUsed, ballsLeft, k)
45+
return {
46+
good: colorsUsed[1] === colorsUsed[0] ? permutations : 0,
47+
total: permutations,
48+
}
49+
}
50+
thisColorMax = Math.min(thisColorMax, balls[colorNum])
51+
for (let i = 0; i <= thisColorMax; i++) {
52+
let match = getValidCombos([...ballsUsed], colorNum + 1)
53+
matches = {
54+
good: matches.good + match.good,
55+
total: matches.total + match.total,
56+
}
57+
ballsUsed[colorNum]++
58+
}
59+
return matches
60+
}
61+
let res = getValidCombos(startArray)
62+
return res.good / res.total
63+
}

0 commit comments

Comments
 (0)