Hey everyone! Basically, I\'ve been given the code of a class that takes two tex
ID: 3527828 • Letter: H
Question
Hey everyone! Basically, I've been given the code of a class that takes two text files and outputs their word count and the % of words that overlap in both, for example:
File read time=2.606 seconds
file #1 words = 17306
file #2 words = 5320
common words = 2345
% of file 1 in overlap = 13.550213798682538
% of file 2 in overlap = 44.078947368421055
Process time=16.0 milliseconds
I am having trouble with this part of the code, which compares the overlapping words. It was orriginally written using ArrayLists and I need to change it to use HashSet or TreeSet in order to lower the compile time:
public static ArrayList<String> getOverlap(ArrayList<String> list1, ArrayList<String> list2) {
ArrayList<String> result = new ArrayList<String>();
int index1 = 0;
int index2 = 0;
while (index1 < list1.size() && index2 < list2.size()) {
int comparison = list1.get(index1).compareTo(list2.get(index2));
if (comparison == 0) {
result.add(list1.get(index1));
index1++;
index2++;
} else if (comparison < 0) {
index1++;
} else { // comparison > 0
index2++;
}
}
return result;
}
So all of the Lists need to be changed to Set, but I am having trouble modifying the rest of the code because Sets don't have indexes so "get" doesn't compile. If you can help in any way, that'd be much appreciated!
Explanation / Answer
public static ArrayList getOverlap(ArrayList list1, ArrayList list2) {
ArrayList result = new ArrayList();
int index1 = 0;
int index2 = 0;
while (index1 < list1.size() ) {
while ( index2 < list2.size() ) { /// change in code
int comparison = list1.get(index1).compareTo(list2.get(index2));
if (comparison == 0) {
result.add(list1.get(index1));
index2++;
}
else {
index2++;
}
}
index1++;
}
}
return result;
}