sum of three numbers from uniformly distributed set equals to zero I'm learning Sedgewick's "Algorithms" and stuck at exercise 1.4.40, cited :

Develop an appropriate mathematical model describing the number of triples of N random int values that sum to 0, where the values are uniformly distributed between –M and M, where M is not small

I do find a close answer for this question :
Sum of three numbers from unformly distributed set equals to zero
However, I don't really understand the two key steps :

pick three values from $[−,]$ that sum to $0$ (this can be done in $3^2+3+1$. Finally we pick the values of the remaining $−3$ positions (can be done in $(2+1)^{−3}$ ways).

Can anyone help to give some more clues on this combinatorics solution ?
Many Thanks!
 A: I don’t really understand the linked answer, but I will try to provide an alternative one.  We’re looking for the number of integer triples $(x_1, x_2, x_3)$ such that
$$
x_1 + x_2 + x_3 = 0
$$
and $-M \le x_i \le M$ for $i = 1, 2, 3$.
Note that we can introduce a change in variables $y_i := x_i + M$; now, our problem becomes equivalent to finding the number of integer triples $(y_1, y_2, y_3)$ such that
$$
y_1 + y_2 + y_3 = 3M
$$
and $0 \le y_i \le 2M$.
This is fairly well-known; see, e.g., Enumerating number of solutions to an equation.  In our case it turns out that the number of such triples is
$$
\binom{3M + (3 - 1)}{3 - 1} - 3 \binom{(M - 1) + (3 - 1)}{3 - 1}\text.
$$
Take for example $M = 46$.  The above expression evaluates to $6487$.  Indeed,
>>> from itertools import product
>>> M = 46
>>> sum(map(lambda xis: sum(xis) == 0, product(range(-M, M + 1), repeat=3)))
6487

Of course, if you’re looking for the probability of this happening, you’ll have to divide the number of such triples by the total number of triples.  You can additionally perform asymptotic analysis on the binomial coefficients if that’s what you’re interested in.
