Unable to get all common items in a multidimensional unsorted array

Criteria for solving the problem: Reduce the complexity to linear. I can use Arrays with a comparable collection type . Duplicates must be allowed.

My concern: My code snippet (methods for getting common elements (strings)):

//Comparable[] items1 = {'a', 'c', 'd', 'e', 'f','d',};
//Comparable[] items2 = {'a', 'c','d', 'e', 'd','f', 'g', 'h'};
//Comparable[] items3 = {'a', 'c','d', 'e','d', 'g'};

//Comparable[][]  items = {items1, items2, items3};

public static ArrayList<Comparable> findCommonElements(Comparable items[][]) {
    int i, j=0; 

    int rows = items.length;

    ArrayList common = new ArrayList(); 
    int []x = new int[rows]; // 

    for(i=0; i<items.length; i++) {
        // here is where I have the problem. It doesn't loop over the entire list in first row.   Therefore, I can only get the first 3. 
        Comparable value = collections[0][x[0]];// obtain the first row. 


        for(j=0;j<items[i].length; j++) {     


             if(items[i][j].compareTo(value)==0) {// compare the values. 
                common.add(value); 
                x[0]++;      

             }
        }
    }
    return common;
}

My conclusion:

[a, c, d]

The correct conclusion:

[a, s, d, e, d]

+4
source share

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


All Articles