How to generate a Cartesian product of a gear array?

I am having trouble figuring out how to create a Cartesian product of a gear array. I have googled around, but I cant seem to be looking for implantation for an iterative language. So I'm trying to figure it out myself, but I got trapped. Allows you to identify the problem a little more clearly.

Let's say I have an array of arrays that looks like this:

A = { {1}, {2, 3}, {4, 5, 6} }

how to go from this to

B = { {1, 2, 4}, {1, 2, 5}, {1, 2, 6}, {1, 3, 4}, {1, 3, 5}, {1, 3, 6} }

edit: now this is just an example, the first array can contain a dynamic number of arrays, and each array has a dynamic size.

If x is the number of elements in the external array, and y [] is a dynamic array of length x, elements containing the number of elements in the internal array. Then x of A becomes y from B, and x from B is the multiplicative sum of y in A. (not proven, taken from examples)

Since x of A is dynamic, the function must be recursive. Here is my attempt.

int** cartesian (int** A, int x, int* y, int* newx, int* newy) {
  *newy = x;
  *newx = 1;
  for (int i = 0; i < x; i++)
    *newx *= y[i];
  int** B = malloc(sizeof(int) * *newx * *newy);

  int xi = 0;
  int* tmp_prod = malloc(sizeof(int) * x);
  recurse(x, 0, y, A, &xi, tmp_prod, B);
  free(tmp_prod);

  return B;
}

void recurse(int x, int xi, int* y, int** A, int* newx, int* temp_inner, int** B) {
  if (xi < x) {
    for (int i = 0; i < y[xi]; i++) {
      temp_inner[xi] = A[xi][i];
      recurse(x, xi + 1, y, A, newx, temp_inner, B);
    }
  } else {
    for (int i = 0; i < x; i++) {
      B[*newx][i] = temp_inner[i];
    }
    (*newx)++;
  }
}

This is how much I got. A recursive function creates a temporary array from one element [recursion depth], and then when it is at maxdepth, it assigns it to B and increments the iterator Bs, returns back and selects the next element [depth of recursion], et c.

The problem is segfaults, and I cannot understand why.

+3
source share
2 answers

, B. newx int, newy ints.

int** B = malloc(sizeof(int*) * *newx);
for (unsigned int i = 0 ; i < *newx; i++) {
   B[i] = malloc(sizeof(int) * *newy);
}

.

+1

, , .

, , , 0. .

const unsigned int x = 3;
unsigned int *ar = calloc(x, sizeof(unsigned int));

, , , , .

, , :

{0, 0, 0} = {1, 2, 4}
{0, 0, 1} = {1, 2, 5}
...
{0, 1, 2} = {1, 3, 6}

0, 1, 2 , .

+1

Source: https://habr.com/ru/post/1771080/


All Articles