Given a pair of integers n
and k
, I want to generate all lists of integers of length n
, containing integers between -k
and +k
, such that the total of the list is equal to zero. How can I do this in the most performant way?
Naively, I could do something like
Select[Tuples[Range[-k,k],n],Total[#]==0&]
but this means I'm generating far more Tuple
s than I need, and for relatively small values of n
and k
, this fails with error SystemException[MemoryAllocationFailure]
I do not need all permutations. Is there a less wasteful way to generate all such lists?