Reputation: 145
I have more or less finished my code, it works with most combinations of letters. It only fails if I enter something like "iiiaa." It returns that 'a' occurs the most, but something like "aaaii" returns that 'a' is also the most. I think the issue has to do with some sort of numerical value because the issue occurs if i list and letter 2 or more times followed by the letter 'a'. My code currently is:
public static char most_frequent_character(String text)
{
int max_counter = 0;
char max_char = 'a';
for (int i = 1; i < text.length(); i++)
{
char current = text.charAt(i);
int counter = count_occurrences(text, current);
char other_char = text.charAt(i-1);
if (counter>count_occurrences(text, other_char))
{
max_char = current;
}
}
return max_char;
}
count_occurrences returns the amount of times a letter appears in the word
Upvotes: 0
Views: 77
Reputation: 1607
this might help you in which we take decision on every character through it's index. and iterate for loop until every character has been checked. after that iterate till List size and get max number of occurrence.
public static char most_frequent_character(String text)
{
List<Integer> t = new ArrayList<Integer>();
List<Character> t2 = new ArrayList<Character>();
//int max_counter = 0;
//char max_char = 'a';
boolean updated = false;
int indexForChar =0;
for (int i = 0; i < text.length(); i++)
{
char other_char = text.charAt(i);
if(t.size()>0)
for(int j=0;j<t.size();j++)
{
if(other_char == t2.get(j))
{
t.set(j, t.get(j)+1);
updated = true;
indexForChar--;
break;
}
}
if(!updated)
{
t.add(1);
t2.add(indexForChar, other_char);
}
updated = false;
indexForChar++;
}
int max = 0;
int index = 0;
for(int j=0;j<t.size();j++)
{
if(max<t.get(j))
{
max = t.get(j);
index= j;
}
}
return t2.get(index);
}
Upvotes: 0
Reputation: 393946
The if (counter>count_occurrences(text, other_char))
condition is wrong, since it decides that the current char is the most occuring char if it has more occurences than the previous one. You should compare it to the current max number of occurences. You already have a max_counter
variable to maintain the current max number of occurences. You should use it. And the loop's index should start at 0.
int max_counter = 0;
char max_char = 'a';
for (int i = 0; i < text.length(); i++)
{
char current = text.charAt(i);
int counter = count_occurrences(text, current);
if (counter>max_counter)
{
max_char = current;
max_counter = counter;
}
}
return max_char;
Upvotes: 2