5

Criteria for solving the problem: Reduce the complexity to linear. I can only use Arrays with collection type of Comparable. Duplicates elements should be allowed.

My concern: My snippet of code(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 output:

[a,c,d]

Correct output:

[a,c,d,e,d]

jrbedard
  • 3,662
  • 5
  • 30
  • 34
Fun-zin
  • 113
  • 6
  • You should use an example involving duplicates so that it is clear how you would handle this edge case. – Tim Biegeleisen Oct 02 '16 at 03:01
  • For this kind of thing, just load the source into a hashmap, then lookup each element of the compared object in the original map. Print or save or compute from there as desired. – Jameson Oct 02 '16 at 03:03
  • @Jameson, unfortunately I am limited to Arrays as my data structure. – Fun-zin Oct 02 '16 at 03:05
  • Thank you everyone for you prompt response. I figured out. I made some changes to my for loop and it works now. Changes are shown below: for(i=collections.length-1, j=0; j – Fun-zin Oct 02 '16 at 03:28

0 Answers0