I would have an array hits[max + 1]
which counts the number of possible combination for each value. max
is n * a
and of course hits[0]
to hits[n - 1]
will remain empty.
The dumb way would be to do n
for-loop (one for each die) and register a hit in hits
for the current sum of the dice.
The less dumb way is to use a bit of combinatorics, where I write out the number of combinations for each ordered shuffle:
there is 1 combination of 1111 (sum = 4)
there are 4 combination of 1112 (sum = 5)
there are 4 combination of 1113 (sum = 6)
...
there are 4 * 3 / 2 combinations of 1123 (sum = 7)
...
there are 4 * 3 * 2 combinations of 1234 (sum = 10)
...
there is 1 combination of aaaa
(sum = n * a
)
You need to spend much less times in the for-loops than the dumb solution.
You get many hits for each iteration instead of just one hit with the dumb method.
Those for-loops just move the (n - 1) partition separations over (1, 2, 3, 4, ..., a
).
The separations can be on the same spot (e.g. they are all between 1 and 2 for the case 1111), but you must not have a separation below 1 or above a
.