I have been working on trying to figure out this algorithm for about 6 hours now and can't seem to come up with a solution. I am trying to count the occurrences of elements inside an array and may two more separate arrays. One for the unique instances, and one for how many times these instances occurs. I found some other thinks on here about array lists and hashMaps, but I am only able to use arrays.
For example, I have this array (already sorted):
{cats, cats, cats, dog, dog, fish}
I am trying to get make an array for the instances, so:
{cats, dog, fish}
And finally, how many times these instances occur:
{3, 2, 1}
Here is the code i have so far:
public void findArrs( String[] words )
{
int counter = 1;
for(int i = 0; i < words.length - 1; i++){
if(!(words[i].equals(words[i+1]))){
counter++;
}
}
String[] unique = new String[counter];
int[] times = new int[counter];
for(int i = 0; i < words.length; i++){
}
}
This is all the code I have after all my attempts.
It would be very simple if you use ArrayList. But since you want especially Arrays, here's my code.
As you can see the real problem is the length of the Arrays that you have to specify before using them. With ArrayLists you wouldn't have to. Also, since the items are sorted prefer using a while loop instead of a for loop. It just looks good.
This is how it could be done using only arrays. The tricky part is you must know the number of items before the array is created. So I had to create my own function to create a bigger array. Actually two, one for the count and one for the unique values.
If you can use Vectors you will be better off. Here is it without vetors:
As mentioned in the comments, if we know the array is in order, then we don't need to search through the entire previous array and can just check uniqueValues directly.
Make unique, times as instance variable so that you can retrieve them from another class using getter methods.
Note: Modified code can be found through comments (for line "Added line". for block between "Added code starts here" to "Added code ends here"). I tried to explain the implementation in code. Please let me know through comments if I need to work more on my documentation skills
String s[] = {"Arranged", "Administered", "Advised", "Administered", "Adapted"};
//Store a pre-defined amount of wordsString k="I have administered and advised him to stay away.";
//A string that you want to match if it contains those wordsString ka[]=k.split("\\s");
//Split the string on evry space occurrence so that it extracts each wordfor(i=0;i<ka.length;i++)
{for(j=0;j<s.length;j++){
if(ka[i].equalsIgnoreCase(s[j]))
{System.out.println("The occurred words are:" +s[j]);
continue;
//Continue is used to find if more that one word has occurred}
}
}
Assuming that the
words
array has at least one element:As other answers have mentioned, this problem could be simplified by using a List such an ArrayList to store the results.
You can achieve it using TreeMap: