I know from reading other questions on the forumn that Array indexing is causing the problem, but I don't know any way around it. I commented where the throw happens. The whole throw is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 35
at assignment4.AnagramUtil.getLargestAnagramGroup(AnagramUtil.java:82)
at assignment4.AnagramTester.main(AnagramTester.java:36)
If anyone has any ideas how I can make this work, let me know. Also, I don't think any more of my methods are relevant in solving this but I can put them here if needed.
/*areAnagrams
* parameters: sorted strings x & y
* returns boolean
* implements sort method
*/
public static boolean areAnagrams(String x, String y)
{
if(sort(x).equals(sort(y)))
return true;
return false;
}
/*
* This function takes a string array and finds the largest anagram group.
* AnagramComparator.insertionSort() sorts the array by placing anagrams together,
* so no sorting is needed.
* I use ArrayList because I want to be able to freely add to the string array.
* returns a new String[]
*/
public static String[] getLargestAnagramGroup(String[] input)
{
String[] s=input;
AnagramComparator.insertionSort(s, new AnagramComparator());
int largestCount = 0, tempCount=1;
ArrayList<String> largest= new ArrayList<String>();
ArrayList<String> temp= new ArrayList<String>();
for(int i=0; i<s.length; i++)
{
//since it's already sorted, we need only to compare.
//add
temp.add(s[i]);
//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 35
if (areAnagrams(s[i],s[i+1])) //at assignment4.AnagramUtil.getLargestAnagramGroup(AnagramUtil.java:82)
{
//add s[i+1] to array list
temp.add(s[i+1]);
tempCount++;
}
else
{
//if tempcount> largestcount, empty contents of largest and make temp largest
if (tempCount>largestCount)
{
if(!largest.isEmpty())
largest.clear();
largest=temp;
largestCount=tempCount;
}
//reset tempcount
tempCount=1;
}
}
String[] result= new String[largest.size()];
for (int j=0;j<largest.size();j++)
result[j]=largest.get(j);
return result;
}
String[] s=input;String[] s = inputcopies the reference, not the array - nowinputandsboth contain references to the one array.