Question

Here i have some problems with find smallest 3 elements in 2- dimensional matrix in C

here is my code:

for (i=0; i<r; i++) {
    for (j=0; j<c; j++) {
        if (m[i][j] < min1) {
            min1 = m[i][j];
            indexi_1 = i;
            indexj_1 = j;
        }
        if (m[i][j] < min2 && indexi_1 != i && indexj_1 != j) {
            min2 = m[i][j];
            indexi_2 = i;
            indexj_2 = j;
        }
    }
    for (j=0; j<c; j++) {
        if (m[i][j] < min3 && m[i][j] != m[indexi_1][indexj_1] && m[i][j] != m[indexi_2][indexj_2]) {
            min3 = m[i][j];
            indexi_3 = i;
            indexj_3 = j;
        }
    }
}

with matrix like this

int m[r][c] = {{33,  4, 23,  2}, {5,  3, 24, 16}, {8, 31,  7,  4},{10,  5,  2,  6}};

getting this output:

 Local minimum (value=2) - row=0, column=3.
 Local minimum (value=2) - row=3, column=2.
 Local minimum (value=4) - row=0, column=1.

so as you see here, the problem only with last min element, i think it doused because of index.

Was it helpful?

Solution

You compare the third minimum against the values of temporary min1 and min2. You must move the third loop after the outer for loop

for (i=0; i<r; i++) {
    for (j=0; j<c; j++) {
        if (m[i][j] < min1) {
            min1 = m[i][j];
            indexi_1 = i;
            indexj_1 = j;
        }
        if (m[i][j] < min2 && indexi_1 != i && indexj_1 != j) {
            min2 = m[i][j];
            indexi_2 = i;
            indexj_2 = j;
        }
    }
}

for (i=0; i<r; i++) {
    for (j=0; j<c; j++) {
        if (m[i][j] < min3 && m[i][j] != m[indexi_1][indexj_1] && m[i][j] != m[indexi_2][indexj_2]) {
            min3 = m[i][j];
            indexi_3 = i;
            indexj_3 = j;
        }
    }
}

Now the last loop will compare against the final first two minima.

OTHER TIPS

Here:

if (m[i][j] < min3 &&
    m[i][j] != m[indexi_1][indexj_1] &&
    m[i][j] != m[indexi_2][indexj_2])

You compare values instead of indices.

Change this line

if (m[i][j] < min3 && m[i][j] != m[indexi_1][indexj_1] && m[i][j] != m[indexi_2][indexj_2])

to

if (m[i][j] < min3 && (indexi_1 != i && indexj_1 != j) && (indexi_2 != i && indexj_2 != j))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top