This question is similar to a question I had several months ago: Generating a numpy array with all combinations of numbers that sum to less than a given number. In that question, I wanted to generate all numbers that summed to at most a constant, given that each element had a certain maximum.
This time I want to calculate all permutations that sum up to exactly that constant. This can be regarded as calculating the unique permutations of integer partitions where each element has a certain maximum. The end result should be stored in a numpy array.
Using a generator, a one liner achieves what we want:
import numpy as np
from itertools import product
K = 3
maxRange = np.array([1,3,2])
states = np.array([i for i in product(*(range(i+1) for i in maxRange)) if sum(i)==K])
giving
array([[0, 1, 2],
[0, 2, 1],
[0, 3, 0],
[1, 0, 2],
[1, 1, 1],
[1, 2, 0]])
I'm having quite slow performance when K=20
and maxRange = [20]*6
. The number of permutations is limited with 53130, but it already takes 20 seconds. My gut feeling tells me this should takes much less than a second.
Does anyone have a faster solution available? I'm having trouble to modify the solution to my earlier question to account for this, because I don't know how to cut off the permutations for which it is no longer possible to add up to exactly K
.
I don't mind solutions that use the @jit
operator from numba... as long as they are faster than what I have now!
Thanks in advance.