I retrieved 200 tweets using jersey API. I want to find two tweets which have the longest common substring. This is what I have got. tweetList is an ArrayList of Tweet Objects. comapreTweets method compares tweet objects for longest substring.
Tweet t1=new Tweet();Tweet t2=new Tweet();
int longestString=0;
for(int i=0;i<tweetList.size();i++)
{int store=0;Tweet comparer=null;
for(int j=i+1;j<tweetList.size();j++)
{
if(j!=i){
int result=tweetList.get(i).compareTweets(tweetList.get(j));
if(result>store){
store=result;
comparer=tweetList.get(j);
}}
}
if(longestString<store)
{
longestString=store;
t1=tweetList.get(i); t2=comparer;
}
}
If I retrieve 200 tweets then this will loop approx. 40000 times. I require a more efficient way.
EDIT
This loop also compares same tweets in inverted order
Suppose my tweetList contains {a,b,c,d} ; when i=1 and j=3 the comparison is between b & d; when i=3 and j=1 the comparison is d & b. How to avoid this.
SOLUTION instead of j=0 it should be j=i+1. It loops for 19701 times.
I believe
19900 timesis a sensible answer. Nearly half of the comparisons in your loops are redundant. You just need to compare the first one to the remaining 199 tweets, the second one to the remaining 198 tweets, and so on. Further optimizaiton better than 19900 times could be possible but I can’t think of one off the top of my head.