Categorías
Programación

Visit all array combinations with a recursive function

A = [1, 2, 3]
B = [4, 5]
C = [6, 7, 8]

# Visit all combinations of A, B and C values
all = [A, B, C]

# General pointer. Points to the current variable: 0 -> A, 1 -> B, ...
gp = 0
# Internal pointer. Points to the item on the current variable
# Example: gp = 1 --> B selected. ip = 2 --> B[2] selected --> B[2] = 5
ip = [0] * len(all)

def iterator(a):
    # For Python to get gp from global scope
    global gp
    # Weird way in Python to create a for loop. Equivalent in C to:
    # for(int i = 0; i < len(a[0]); i++)
    for i in range(0, len(a[0])):
        # Store current internal pointer
        ip[gp] = i
        # If a has more variables (e.g. a = [[1,2,3], [4,5], [6,7,8]])
        if len(a) > 1:
            # Create subset for the remaining variables, i.e. [[4,5], [6,7,8]]
            # Pythonic way to create an array subset from a given index until
            # end of the array
            b = a[1:]
            # Increase global index as we are about to sweep next variables
            gp = gp + 1
            # Iterate the rest of variables, i.e. [[4,5], [6,7,8]]
            iterator(b)
            # We came back from lower variables (B and C), so restoring global 
            # pointer to point again to A
            gp = gp - 1
        else:
            # Just for result visualization purposes
            str = "["
            # External index and internal index
            for i_ext, i_in in enumerate(ip):
                str = str + "{}, ".format(all[i_ext][i_in])
            # Remove last ", " and add closing ] (cosmetic)
            str = str.strip(", ") + "]"
            print("Indexes = {} --> Values: {}".format(ip, str))

            # ip contains the indexes to all internal variables. Example:
            # Iterating at A[3], B[2], C[1] --> ig = [3, 2, 1] 

iterator(all)

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.