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)

Result

Given the input variables:

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

the output of the script is as follows:

Indexes = [0, 0, 0] --> Values: [1, 4, 6]
Indexes = [0, 0, 1] --> Values: [1, 4, 7]
Indexes = [0, 0, 2] --> Values: [1, 4, 8]
Indexes = [0, 1, 0] --> Values: [1, 5, 6]
Indexes = [0, 1, 1] --> Values: [1, 5, 7]
Indexes = [0, 1, 2] --> Values: [1, 5, 8]
Indexes = [1, 0, 0] --> Values: [2, 4, 6]
Indexes = [1, 0, 1] --> Values: [2, 4, 7]
Indexes = [1, 0, 2] --> Values: [2, 4, 8]
Indexes = [1, 1, 0] --> Values: [2, 5, 6]
Indexes = [1, 1, 1] --> Values: [2, 5, 7]
Indexes = [1, 1, 2] --> Values: [2, 5, 8]
Indexes = [2, 0, 0] --> Values: [3, 4, 6]
Indexes = [2, 0, 1] --> Values: [3, 4, 7]
Indexes = [2, 0, 2] --> Values: [3, 4, 8]
Indexes = [2, 1, 0] --> Values: [3, 5, 6]
Indexes = [2, 1, 1] --> Values: [3, 5, 7]
Indexes = [2, 1, 2] --> Values: [3, 5, 8]

Entradas relacionadas

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.