How Can I calculate number of combinations/permutations with certain rules Lets say I have 4 balls and when each  ball is drawn it can be any value between 1-40 inclusive.
If order isn't important then it would just be $40\cdot 39\cdot 38\cdot 37/4!$
But what if ball 1 had to be between 2 and 9, ball 2 between 9 and 20 and ball 4 had to be between 35 and 40
How would I go about calculating this?
Would it be $8 \cdot 11 \cdot 39 \cdot 5 / 4! $?
 A: Since the constraints are inclusive the problem is somewhat harder.
The answer is $ 7 \cdot 12 \cdot 6 \cdot 5 + 7 \cdot 12 \cdot 32 \cdot 6 + 11 \cdot 6 \cdot 5 + 11 \cdot 32 \cdot 6$. 
We partition the possibilities based on 


*

*Whether the first number is $9$ or between $2..8$

*Whether the third number is between $35..40$ or not.
The first term counts the number of ways when the first number is between $1..8$ and the third number is in $35..40$ the other terms account for the remaining $3$ cases.
A: We can separate this into two cases: a) Ball 1 is not 9 and b) Ball 1 is 9:
In the 1st case, we have 7 choices for Ball 1, 12 choices for Ball 2, 6 choices for Ball 4, and 37 choices for Ball 3, giving $7\cdot12\cdot37\cdot6$ possibilities.
In the 2nd case, we have 1 choice for Ball 1, 11 choices for Ball 2, 6 choices for Ball 4, and 37 choices for Ball 3, giving $1\cdot11\cdot37\cdot6$ possibilities.
Therefore there are $7\cdot12\cdot37\cdot6+1\cdot11\cdot37\cdot6=21,090$ possibilities.
(NOTE: I am assuming that Ball 1 cannot be 1, as stated in the problem.)
A: Could a mathematician please generalize the solution to the following question:
r1min <= b1 <= r1max,
r2min <= b2 <= r2max,
...
rNmin <= bX <= rNmax,
b1 <b2 <... <bX.
How to determine the number of solutions (combinations of x balls b with n specified different ranges r), is there pseudocode or programs for it?
