extract unique rows of 2d array

hi,

i have a 2d array with entries like

1.2 2.3

2.4 4.5

1.2 2.3

1.9 3.5


I want to extract all the unique rows of the 2d array like this

1.2 2.3

2.4 4.5

1.9 3.5



Any suggestions on how I can do this?

Thanks
The easiest way I think is to store the unique rows in an another array. That way you can compare to see if the row is unique or not.
My English isn't good enough but I will try to explain what I was trying to accomplish.
So, for each row (r1) I will cycle down the rows to see if there is a row (r2) that is completely same as the r1. If that is the case, I will add index of r2 to my list of no-no indexes. Then, I will copy all rows from original array to the result array, except rows that are in my no-no list.
It looks like my code works, but I'm not sure :D
You didn't mention - C or C++? As you can C, my code is written in C.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdio.h>
#define MAX 50
int main() {
    int rows, cols;
    float arr[MAX][MAX];

    printf("No. of rows: "); scanf("%d", &rows);
    printf("No. of cols: "); scanf("%d", &cols);
    printf("\n");

    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            scanf("%f", &arr[i][j]);

    int nonolist[MAX],
        count = 0;
    for (int r1 = 0; r1 < rows; r1++) {
        for (int r2 = r1 + 1; r2 < rows; r2++) {
            bool same = false;
            for (int c = 0; c < cols; c++) {
                if (arr[r2][c] == arr[r1][c])
                    same = true;
                else {
                    same = false;
                    break;
                }
            }
            if (same) {
                nonolist[count] = r2;
                count++;
            }
        }
    }

    printf("\n");
    for (int i = 0; i < count; i++)
        printf("%d ", nonolist[i]);
    printf("\n\n");

    float result[MAX][MAX];
    int rows1 = 0;
    for (int r = 0; r < rows; r++) {
        bool nono = false;
        for (int i = 0; i < count; i++) {
            if (nonolist[i] == r) {
                nono = true;
                break;
            }
        }
        if (nono) continue;
        for (int c = 0; c < cols; c++) {
            result[rows1][c] = arr[r][c];
            printf("%.1f ", result[rows1][c]);
        }
        printf("\n");
        rows1++;
    }
    return 0;
}
Last edited on
If you had the 2D array stored as a std::vector of vectors (each row as one std::vector) then you could use the relational operators of the std::vector
http://www.cplusplus.com/reference/vector/vector/operators/

However, your values are floating point values and the equality comparison of floating points is tricky. Therefore, the use of std::equal with appropriate custom binary predicate is recommended.
Topic archived. No new replies allowed.