Home > Software design >  Displaying the values of an n-dimension array as a string
Displaying the values of an n-dimension array as a string

Time:11-06

Provided that we have an integer array of arbitrary depth, how would we traverse through it in order to build a string that represents the array as a C-style initialization?

For instance:

int arr3D[2][3][2]  = { {{0, 1}, {2, 3}, {4, 5}}, {{6, 7}, {8, 9}, {10, 11}} };

We only know:

  • the total number of values (in this case 12)
  • the number of "dimensions" (in this case 3)
  • each of the dimension indexes (in this case 2,3,2)
  • the values 0,1,2,3,4,5,6,7,8,9,10,11

How can we make a string out of that, that looks like this:
"{{{0,1},{2,3},{4,5}},{{6,7},{8,9},{10,11}}}" ?


Evidently, this can be done with a nested nested loop, but that would only work with a definite set of dimensions (3). What if we have 10 dimensions? That made me think I can use recursion, but then it became confusing when and how to put { } characters. I am currently thinking about a single linear scan that intelligently inserts { and } characters in the string 0,1,2,3,4,5,6,7,8,9,10,11 but I feel like the real-world approach would be something like an indefinite n-tree branch traversing algorithm.

CodePudding user response:

As you mentioned there are no need for the ndim for loops, what you could do is to use concepts like stride. Like then in how many count you change a dimention and then you can build you string.

since you have not written any example code to see what you are interested as you function. I will write kind of psudo code how this could be done. in final case, dimetions should be input and stride calculated dynamically. as well it is better to build an string and print at the end, but for just the purpose of algo parts I am just using character by character printf.

void print_mat(int* ptr, int ndims, int* dims){
    int *stride = malloc(sizeof(int)* ndims);
    // create stride array same size of dims
    stride[ndims -1] = dims[ndims - 1];
    for(int j = ndims - 2 ; j >= 0; j--)
        stride[j] = dims[j] * stride[j   1];
    // loop over all elements, stride[0] has the length
    for(int idx = 0 ; idx < stride[0]; idx  ){
        // print open { for each start dimension
        for(int i = 0; i < ndims; i  )
            if (idx % stride[i] == 0){printf("{");}

        printf("%d", ptr[idx]);
        // print close } for each end dimension
        for(int i = 0; i < ndims; i  )
            if ((idx   1) % stride[ndims - i - 1] == 0){printf("}");}

        printf(", "); // comma after each element
    }
    printf("\b\b \n"); // clear extra , at end (may not support in all terminals)
    free(stride);
}

int main()
{
    int arr3D[2][3][2]  = { {{0, 1}, {2, 3}, {4, 5}}, {{6, 7}, {8, 9}, {10, 11}} };
    int dims[3] = {2, 3, 2};
    print_mat(&arr3D[0][0][0], 3, dims);
    return 0;

}

output:

{{{0, 1}, {2, 3}, {4, 5}}, {{6, 7}, {8, 9}, {10, 11}}}
  • Related