All possible integer array of fixed length for a given norm?

Question:

Given d and t, positive integers, i would like to generate all possible 1D arrays of length d such that coordinates are positive integers and their sum is less or equal to t. For example, for d=2, and t=2, such possibilities are : [0,0], [1,0], [0,1], [2,0], [0,2] and [1,1].

I am not sure how to handle this problem, especially for high d where looping over each coordinates is prohibitive, is there an efficient way to do so ? I am working in python and also i wonder if there is may be a way to solve this using Itertools.

Asked By: BabaUtah

||

Answers:

One approach that you can do this is to use recursion. Additionally memory efficiency and time efficiency while working with list is only possible with generators as used in the following code.

def generate_arrays(d, t):
    if d == 0: # if d is zero is there is nothing to construct hence empty list
        yield []
        return
    for i in range(0, t+1):
        for arr in generate_arrays(d-1, t-i):
            yield [i] + arr

testing tha function:

for arr in generate_arrays(d=2, t=2):
    print(arr)

and the output is:

[1, 1]
[1, 0]
[0, 1]
[2, 0]
[0, 2]
[0, 0]