Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

An optimization to calculate the intersection between 2 sequences using java Sets #69

Merged
merged 1 commit into from
Dec 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 6 additions & 21 deletions src/main/java/uk/ac/ebi/eva/evaseqcol/service/SeqColService.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -481,28 +482,12 @@ public List<String> getCommonElementsDistinct(List<String> seqColAFields, List<S

/**
* Return the number of common elements between listA and listB
* Note: Time complexity for this method is about O(n²)*/
* */
public Integer getCommonElementsCount(List<?> listA, List<?> listB) {
List<?> listALocal = new ArrayList<>(listA); // we shouldn't be making changes on the actual lists
List<?> listBLocal = new ArrayList<>(listB);
int count = 0;
// Looping over the smallest list will sometimes be time saver
if (listALocal.size() < listBLocal.size()) {
for (Object element : listALocal) {
if (listBLocal.contains(element)) {
count ++;
listBLocal.remove(element);
}
}
} else {
for (Object element : listBLocal) {
if (listALocal.contains(element)) {
count++;
listALocal.remove(element);
}
}
}
return count;
Set<?> listALocal = new HashSet<>(listA); // we shouldn't be making changes on the actual lists
Set<?> listBLocal = new HashSet<>(listB);
listALocal.retainAll(listBLocal);
return listALocal.size();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,12 @@ void A_And_B_Same_OrderTest() {
assertFalse(seqColService.check_A_And_B_Same_Order(listA5, listB5));
}

@Test
void commonElementsCountTest() {
List<String> listA1 = new ArrayList<>(Arrays.asList("chr1", "chr2", "chr3", "A"));
List<String> listA2 = new ArrayList<>(Arrays.asList("chr1", "chr5", "chr3", "M", "A"));

assertEquals(3, seqColService.getCommonElementsCount(listA1, listA2));
}

}