0

我有 20 个不同的可变长度数组,每个数组都有一个唯一值,我需要计算这些数组的所有可能组合:

#define LENGTH_COUNT 6
#define WIDTH_COUNT 4
etc, for all 20 arrays:

int length[LENGTH_COUNT];
int width[WIDTH_COUNT];
int height[HEIGHT_COUNT];
int weight[WEIGHT_COUNT];
int growth[GROWTH_COUNT];
int decay[DECAY_COUNT];
int sound[SOUND_COUNT];
int texture[TEXTURE_COUNT];
int moisture[MOISTURE_COUNT];
int volume[VOLUME_COUNT];
int speed[SPEED_COUNT];
int color[COLOR_COUNT];
int purpose[PURPOSE_COUNT];
int delay[DELAY_COUNT];
int vibrancy[VIBRANCY_COUNT];
int brix[BRIX_COUNT];
int ripeness[RIPENESS_COUNT];
int mold[MOLD_COUNT];
int temp[TEMP_COUNT];
int language[LANGUAGE_COUNT];


void iterate(void)
{
    for (int i = 0; i < LENGTH_COUNT; ++i)
          for (int j = 0; j < WIDTH_COUNT; ++j)
                for (int k = 0; k < HEIGHT_COUNT; ++k)
                // etc for all 20 arrays
                    int value = doSomething(length[i], width[j], height[k].....);
}

必须有一种不那么脑残的方法来做到这一点。我的一个想法是:

#define ARRAY_COUNT  20
#define MAX_LENGTH 12   // the longest array length is 12
int arrays[ARRAY_COUNT][MAX_LENGTH];

但如果我要这样做,我不知道如何做与我在 iterate 函数中所做的等效的事情。有任何想法吗?

4

2 回答 2

1

您可以创建(未经测试/未编译):

int *arrays[] = { first_arr, second_arr, ... }; // array of arrays
int maxes[] = { FIRST_ARR_MAX, SECOND_ARR_MAX, ... }; // array of array lengths
int counter[NUM_ARRAYS] = {0}; // initialize a counter to 0 for each of the arrays.

int state = 0;

while (true) {
    doSomething(first_arr[counter[0]], second_arr[counter[1]], ... );

    // Update the counter.
    int i;
    for (i = NUM_ARRAYS - 1; i >= 0; i--) {
        counter[i]++;
        // If incrementing the current counter didn't overflow, we're good, so we break.
        if (counter[i] < maxes[i]) {
            break;
        } else {
            // Overflow by setting the counter to 0.
            counter[i] = 0;
            // Now we will fall through and move to the next counter.
        }
    }
    // Check for all 0's intelligently.  State == 0 means counter[0] is 0.
    // If it's no longer 0, move to state 1.
    if (state == 0 && counter[0] > 0) {
        state = 1;
    } else (state == 1 && counter[0] == 0) {
        break;
    }
} 
于 2012-04-05T01:33:00.660 回答
0

这似乎有效,虽然我没有彻底测试过。它在 python 中,但希望很清楚如何在您的情况下使用。重要的一点是,它将问题划分为更容易的部分,以避免深度嵌套的 for 循环。

test_arrays = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
def combine(partial, next_array):
    new_array = []
    for p in partial:
        if not isinstance(p, list):
            p = [p]
        for v in next_array:
            new_array.append(p + [v])
    return new_array

def combinations(arrays):
    base = arrays[0]
    for i in xrange(1, len(arrays)):
        base = combine(base, arrays[i])
    return base

print combinations(test_arrays)

但正如上面其他人所说,您几乎可以肯定根本不想这样做。更好的方法是选择随机组合并测试/评估它们。可以使用各种算法来改进朴素随机抽样,但哪种算法合适取决于您的应用程序。

于 2012-04-05T02:04:55.557 回答