//With this method, I input a string and return an array that contains a sorted list of characters as per the frequency. Eg: If i input "apple", the out put should be p,a,l,e, How do I do this?
public static ArrayList<Character> characterFreqDist(String statement)
{
char[] Array = statement.toCharArray();
int length = Array.length;
int most_frequent_count = 0;
char most_freq_character = '\0';
char[] Final_Array = new char[length];
ArrayList<Character> Sorted_Array = new ArrayList<Character>();
for(int loop = 0 ; loop<length ; loop++)
{
most_freq_character = '\0';
most_frequent_count = 0;
for(int i = 0; i<length ; i++)
{
char single_character = Array[i] ;
int counter = 0;
for(int j = 0; j<length ; j++)
{
if (single_character == Array[j])
{
counter++;
}
}
if (counter > most_frequent_count)
{
most_frequent_count = counter;
most_freq_character = single_character;
}
}
Sorted_Array.add(most_freq_character);
int index = 0;
for (int k = 0; k < length; k++)
{
if(Array[k] != most_freq_character)
Final_Array[index++] = Array[k];
}
Array = Final_Array.clone();
length = Array.length;
}
return Sorted_Array;
}
guffadi
0
Newbie Poster
Recommended Answers
Jump to PostIt can be done using loops like that, but you have to do something like:
…while some input remains... find the most frequent character (like in your code) add the right number of that character to the output remove all instances of that character from the input
All 6 Replies
JamesCherrill
4,733
Most Valuable Poster
Team Colleague
Featured Poster
guffadi
0
Newbie Poster
JamesCherrill
4,733
Most Valuable Poster
Team Colleague
Featured Poster
guffadi
0
Newbie Poster
JamesCherrill
4,733
Most Valuable Poster
Team Colleague
Featured Poster
JamesCherrill
4,733
Most Valuable Poster
Team Colleague
Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.