• ### Random numbers that add up to a certain number

Hey guys, how can I randomly generate a number of values which add up to a given value? So say I want 4 numbers that add up to 16: they could be (4, 4, 4, 4) or (10, 2, 2, 2) or (4, 3, 5, 4) etc etc. does anyone know a way of doing this efficiently? I would also like to be able to control how many of these numbers are allowed to be zero, if any.

• Posts 11 | Views 189
• Have you tried this approach < https://stackoverflow.com/a/8064754 >?

• @Nicolas-Danet
this is some good idea.... i was curious, so i just made a patch according that idea and somehow avoids zeros.... however, the disadvantage is, that there are many repetitions in a list of output numbers.... maybe someone finds it useful....random_to_certain_sum.pd

• Here is another solution:
rand12.pd

• Here is another attempt (because the 9 is not possible in my first try... )
rand12b.pd

There is also a fisher yates algorithm implemented with lua for randomizing the list.
The new problem is: the combinations of one 9 and three 1's seem over representated because every time there is a 9 there also need to be three 1's...
So perhaps my first attempt has a more balanced result.

The idea is to start with a list of zeros and add 1 randomly until the sum is reached.

Implementation: random_to_sum.pd

• @ingox thats nice. i modified it a bit, to avoid zeros (but now the sum(16) needs to be at least as large as the list length(4) to give an accurate result):
random_to_sum_1.pd

• Without zeros: random_to_sum2.pd