Nested loop to access each record index

60 Views Asked by At

I have a text file that has 4 records and each record consists of 4 values. I also have 3D matrix where each item in this matrix is one of those records. I want to iterate over this matrix and get for each item its record index from the text file.

Here is a simple example of what the data looks like:

float res[4][3][4] = {
    {{1.1, 2.2, 3.3, 4.4}, {4.4, 5.5, 6.6, 7.7}, {7.7, 8.8, 9.9, 0.0}},
    {{4.4, 5.5, 6.6, 7.7}, {1.1, 2.2, 3.3, 4.4}, {7.7, 8.8, 9.9, 0.0}},
    {{7.7, 8.8, 9.9, 0.0}, {1.1, 2.2, 3.3, 4.4}, {4.4, 5.5, 6.6, 7.7}},
    {{1.1, 2.2, 3.3, 4.4},{5.5, 1.1, 4.4, 6.6}, {4.4, 5.5, 6.6, 7.7}}
};

float records[4][4] = {
    {7.7, 8.8, 9.9, 0.0},
    {1.1, 2.2, 3.3, 4.4},
    {4.4, 5.5, 6.6, 7.7},
    {5.5, 1.1, 4.4, 6.6}
};

I want the output to be:

results[4][3]= {
    {2, 3, 1},
    {3, 2, 1},
    {1, 2, 3},
    {2, 4, 3}
}

I implemented this code:

int *rowIndices = (int *)malloc(4 * sizeof(int));

for (int i = 0; i < 4; i++) {
    int rowIndex = -1; // Initialize to -1 if no matching row is found
    printf("Results for record %d:\n", i + 1);
    for (int j = 0; j < 3; j++) {
        int match = 1; // Assume a match
        printf("Residue %d: ", j + 1);
        for (int k = 0; k < 4; k++) {
            printf("res %f: ", res[i][j][k]);
            printf("record %f: ", records[j][k]);
            if (res[i][j][k] != records[j][k]) {
                match = 0; // Not a match
                break;
            }
        }
        if (match) {
            printf("%d ", j);
            rowIndices[i] = j;
        }
        printf("\n");
    }
    printf("Row index for res[%d]: %d\n", i, rowIndices[i]);
}

Inside the third loop when it compares the first value of res and first value record and they don't match it automatically goes for the next res and next record. I want it to compare each res with all records and get its index because it must be there.

0

There are 0 best solutions below