HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Enumerating all n-tuples over a finite domain

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
finitedomainallenumeratingovertuples

Problem

I would like to create an algorithm which takes in an integer n and returns an array whose entries give all n-tuples of nonnegative integers each of which is at most n, so like

  • A[n][0] = [0,0,0,...,0],



  • A[n][1] = [1,0,0,...,0], ...,



  • A[n][n^(n+1)]=[n,n,n,...,n],



that kind of thing.

If n is small, I can manually create n-many for loops to do this, but in general I would like to allow n to be large. Is there an easy workaround? Any help would be appreciated.

Solution

Use recursion. Something like this:

def f(l, k):
    if l==0:
        yield []
    else:
        for i in range(k):
            for L in f(l-1, k):
                yield [i]+L


Here f(l, k) produces all lists of length l all of whose entries are in the range 0..k-1. The idea is that if you have all lists of length l-1 (the output of f(l-1, k)) you can use that to generate all lists of length l, by using a for-loop.

If you're not familiar with that Python syntax, try this variant:

def f(l, k):
    if l==0:
        return [[]]
    t = [] 
    for i in range(k):
        for L in f(l-1, k):
            t.append([i]+L)
    return t


Note that [i] is a list containing a single element, i, and + is the list concatenation operator, so [i] + L is a list obtained by prepending the element i to the front of list L.

Code Snippets

def f(l, k):
    if l==0:
        yield []
    else:
        for i in range(k):
            for L in f(l-1, k):
                yield [i]+L
def f(l, k):
    if l==0:
        return [[]]
    t = [] 
    for i in range(k):
        for L in f(l-1, k):
            t.append([i]+L)
    return t

Context

StackExchange Computer Science Q#40931, answer score: 3

Revisions (0)

No revisions yet.