0

I am trying to find the percentage of how many elements in two ArrayList<Point>s match, but I am at a dead end. Can anyone help?

This is what I tried to do, I don't know if it's true or applicable:

int i;
int count = 0;

ArrayList<Point> firstInter= array1; //  output from other class
ArrayList<Point> secondInter = array2; //output from other class
int size= firstInter.size(); //they have the same size

for (i = 0; i < size; i++) {
    if (firstInter.get(i) == secondInter.get(i)) {
        count1++;
    }
}

double percentage1 = count / size;
Turing85
  • 13,364
  • 5
  • 27
  • 49

2 Answers2

1

You need to find the intersection of both lists. In detail: The number of elements of the first list that are also contained in the second list:

List<Point> first = ...;
List<Point> second = ...;
int count = 0;

for (Point p : first) {
    if (second.contains(p)) count++;
}

// assuming, first and second have equal size
double percentage = (double)count / first.size();

Containment operations are much more efficient in a Set than a List, so if you have a lot of elements, it might be considerably faster, to use a Set for second:

Set<Point> second = new HashSet<Point>(secondList);

Fortunately, a Set already offers a method to perform an intersection operation: Set.retainAll(Collection other). Java API Docs:

Retains only the elements in this set that are contained in the specified collection (optional operation).

So to get the intersection of two collections, we can simply use this method:

Collection<Point> first = ...; // should be a Set for maximum performance
Set<Point> second = new HashSet<Point>(...);

second.retainAll(first);

// assuming, both point lists have equal size
double percentage = (double)count / first.size();

Note: All this code only works if class Point has correctly overwritten equals and hashcode. See https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java.

Community
  • 1
  • 1
isnot2bad
  • 22,602
  • 2
  • 27
  • 43
0

You can use the method intersection from: org.apache.commons.collections.CollectionUtils:

int intersectionSize = CollectionUtils.intersection(firstInter, secondInter).size();

As for "percentage", the question is percentage of what? the union ? Either way it shouldn't be difficult, you can do something like:

return 100 * intersectionSize / (firstInter.size() + secondInter.size());
Nir Alfasi
  • 49,889
  • 11
  • 75
  • 119