Find character with most occurrences in string?
input.GroupBy(x => x).OrderByDescending(x => x.Count()).First().Key
Notes:
- if you need this to work on ancient (2.0) versions of .Net consider LinqBridge. If you can't use C# 3.0 (targeting .Net 2.0) you probably better off with other solutions due to missing lambda support. Another .Net 2.0+ option is covered in xanatos answer.
- for the case of
"aaaabbbb"
only one of those will be returned (thanks xanatos for comment). If you need all of the elements with maximum count, use Albin's solution instead. - due to sorting this if O(n log n) solution. If you need better than that - find Max value by linear search instead of sorting first which will give O(n). See LINQ: How to perform .Max() on a property of all objects in a collection and return the object with maximum value
Finding the most frequent character in a string javascript
This will loop over every character in the string and keep track of each character's count and the character with the maximum count:
var exp = '3553853335' ;
var expCounts = {};
var maxKey = '';
for(var i = 0; i < exp.length; i++)
{
var key = exp[i];
if(!expCounts[key]){
expCounts[key] = 0;
}
expCounts[key]++;
if(maxKey == '' || expCounts[key] > expCounts[maxKey]){
maxKey = key;
}
}
console.debug(maxKey + ":" + expCounts[maxKey]);
Update:
Here is an ES6 version that will handle strings where multiple character have the same max count
function maxCount(input) {
const {max, ...counts} = (input || "").split("").reduce(
(a, c) => {
a[c] = a[c] ? a[c] + 1 : 1;
a.max = a.max < a[c] ? a[c] : a.max;
return a;
},
{ max: 0 }
);
return Object.entries(counts).filter(([k, v]) => v === max);
}
Example (please excuse the crude output):
maxCount('--aaaa1111--').join(' | ').replace(/,/g, ':');
outputs 1:4 | -:4 | a:4
How to find the most frequently occurring character in a string with Java?
You already got your answer here: https://stackoverflow.com/a/21749133/1661864
It's a most easy way I can imagine.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MaximumOccurringChar {
static final String TEST_CASE_1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today. Help!";
public static void main(String[] args) {
MaximumOccurringChar test = new MaximumOccurringChar();
List<Character> result = test.maximumOccurringChars(TEST_CASE_1, true);
System.out.println(result);
}
public List<Character> maximumOccurringChars(String str) {
return maximumOccurringChars(str, false);
}
// set skipSpaces true if you want to skip spaces
public List<Character> maximumOccurringChars(String str, Boolean skipSpaces) {
Map<Character, Integer> map = new HashMap<>();
List<Character> occurrences = new ArrayList<>();
int maxOccurring = 0;
// creates map of all characters
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (skipSpaces && ch == ' ') // skips spaces if needed
continue;
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
if (map.get(ch) > maxOccurring) {
maxOccurring = map.get(ch); // saves max occurring
}
}
// finds all characters with maxOccurring and adds it to occurrences List
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == maxOccurring) {
occurrences.add(entry.getKey());
}
}
return occurrences;
}
}
Find most occurred character in a String
If ArrayList
is a requirement: After you built your ArrayList make a loop again over characters from input and use
Collections.frequency(list, c)
to get a number of each character occurrences which you will put into max if max is smaller.
PS. to make it more "smart" :-) you can create a Set<Character>
in parallel with your list
to have distinct characters from your input, and then loop through that set to get Collections.frequency(list, c)
.
Or you can remove tested character from list by using removeAll
method only, if you do not need your list
anymore - at the end it will be empty.
UPDATED - working code - there are 2 variations with removeAll usage - one for first most character and second for last if there are more than 2 characters with the same number of occurrences. As long as you created your list
inside the method and need only most Character returned there is no reason to keep list
unchanged. It is gone at the end of method anyway.
note: (I made them static only because for testing I used main - you do not need to do that) - pick one :
public static void main(String... args) {
String input = "This is a simple test string+++++";
System.out.println("charCounterV1First: first most Character: "
+ charCounterV1First(input));
System.out.println("charCounterV1Last: last most Character: "
+ charCounterV1Last(input));
}
public static char charCounterV1First(String input) {
ArrayList<Character> list = new ArrayList<Character>();
for (Character c : input.toCharArray()) {
list.add(c);
}
int max = 0;
Character mostChar = null;
ArrayList<Character> remList = new ArrayList<Character>();
while (list.size() > 0) {
Character nextChar = list.get(0);
int count = Collections.frequency(list, nextChar);
if (count > max) {
max = count;
mostChar = nextChar;
}
remList.clear();
remList.add(nextChar);
list.removeAll(remList);
}
return mostChar;
}
public static char charCounterV1Last(String input) {
ArrayList<Character> list = new ArrayList<Character>();
for (Character c : input.toCharArray()) {
list.add(c);
}
int max = 0;
Character mostChar = null;
ArrayList<Character> remList = new ArrayList<Character>();
while (list.size() > 0) {
Character nextChar = list.get(0);
int count = Collections.frequency(list, nextChar);
if (count >= max) {
max = count;
mostChar = nextChar;
}
remList.clear();
remList.add(nextChar);
list.removeAll(remList);
}
return mostChar;
}
Finding the most frequent character in a string
There are many ways to do this shorter. For example, you can use the Counter
class (in Python 2.7 or later):
import collections
s = "helloworld"
print(collections.Counter(s).most_common(1)[0])
If you don't have that, you can do the tally manually (2.5 or later has defaultdict
):
d = collections.defaultdict(int)
for c in s:
d[c] += 1
print(sorted(d.items(), key=lambda x: x[1], reverse=True)[0])
Having said that, there's nothing too terribly wrong with your implementation.
Find the most occurring character in a string
Here's a way that creates a reverse frequency dictionary. I also made the creation of the frequency dictionary and its reverse fairly succinct by using a dictionary comprehension:
def most_frequent_letter(s):
st = s.lower().replace(' ', '')
frequencies = {}
frequencies = {item: frequencies.setdefault(item, 0) + 1 for item in st}
rev_freq = {count: key for key, count in frequencies.items()}
return rev_freq[max(rev_freq)]
print(most_frequent_letter('nnmmmaaa')) # -> a
Finding the most frequent character in a string using binary search
As your characters are grouped the problem is reduced to finding longest sequence of consequent letters...
So yes you can use binary search to find the size of each sequence which is O(m.log(n))
where m<=n
is the number of sequences (distinct letters). As you stated m<=26
you can consider it as constant leading to O(log(n))
The algo would be something like this:
consider your string is
char s[n];
and resultint l=0;
for (i=0;i<n;)
binary search
j
positionof last character the where
s[i]==s[j]
wherei <= j < n
remember max
l=max(l , j+1-i)
i=j+1
continue
the loop from #2
However note that any letter can have only single sequence so strings like abaaaaaa
will not work.
Find the most frequent occurring character in a string
You could just use the character itself as key to the dictionary.
let string = "abbcde"
var counters = [Character: Int]()
for c in string {
if let count = counters[c] {
counters[c] = count + 1
} else {
counters[c] = 1
}
}
let maxElement = counters.reduce(counters.first!) { $1.1 > $0.1 ? $1 : $0 }
print(maxElement.0) // prints "b"
Updated to swift 4 syntax.
Finding most frequent char for a given word
I don't know the exact implementation of OrderByDescending, but I assume it is not faster than O(n*log n). But finding a maximum value should only be O(n). Hence you can save some time if you don't sort, but only look for the maximum:
public static char MostAparitionsChar(string word)
{
char result = ' ';
int max = int.MinValue;
foreach(var grouping in word.GroupBy(x => x))
{
int count = grouping.Count();
if(count > max)
{
max = count;
result = grouping.Key;
}
}
return result;
}
Finding the most repeated character in a string in R
Using base R, we can separate every character and calculate their occurrence using table
and return the one with max frequency.
most_repeated_character <- function(x) {
tab <- table(strsplit(x, '')[[1]])
names(tab)[tab == max(tab)]
}
most_repeated_character('apple')
#[1] "p"
most_repeated_character('potato')
#[1] "o" "t"
Related Topics
Elevating Privileges Doesn't Work with Useshellexecute=False
Dataview.Sort - More Than Just Asc/Desc (Need Custom Sort)
Sqlparameter Does Not Allows Table Name - Other Options Without SQL Injection Attack
Accordion in Windows Forms Datagridview
Convert from Scientific Notation String to Float in C#
Insert into C# with SQLcommand
When a Class Is Inherited from List<>, Xmlserializer Doesn't Serialize Other Attributes
Winforms Radiobuttonlist Doesn't Exist
Resharper Warning - Access to Modified Closure
Determining If File Exists Using C# and Resolving Unc Path
Show a Child Form in the Centre of Parent Form in C#
C# Generics Won't Allow Delegate Type Constraints
How to Detect If a Debugger Is Attached to Another Process from C#
Invoking Methods with Optional Parameters Through Reflection