Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I want to display count of repeating letters in an array using dictionary.
How to implement this?
below is the sample code. please explain further implementation of logic.

What I have tried:

string[] inputArray = new string[] { "Hello1", "Hello2", "Hello3" };
            var map = new Dictionary<int, string>();
            for (int i = 0; i < inputArray.Length; i++)
            {
                map.Add(i,inputArray[i]);
            }

            foreach (var mapitem in map)
            {
                int key = mapitem.Key;
                string value = mapitem.Value;
                
            }
Posted
Updated 30-Jun-19 0:15am
Comments
Dominic Burford 28-Jun-19 5:34am    
What exactly are you stuck on? Are you getting an error? Is your code failing? Can you provide more details as to what the problem is.
Virendra S from Bangalore, Karnataka 28-Jun-19 5:48am    
I am stuck at logic side, current code is executing without error, not getting implementation idea to check count of repeating letters.
BillWoodruff 28-Jun-19 22:26pm    
I only see three repetitions of one letter: 'l' :)

First off, your Dictionary is wrong: you want a count of repeating characters, so your Key needs to be the unique part - the character - and the value should be the number of them
C#
Dictionary<char, int> charCounts = new Dictionary<char, int>();
Now you can check if a character exists in the dictionary each time you come across it, and either add it or increment the count.
Secondly, your code doesn't check for letters at all, it just loops on the strings in the array, and copies them into a dictionary, using the array index as the count - which is completely pointless.

Go back to your homework question, and read it carefully. If you are supposed to count characters, then that means processing each string in the array, not counting strings at all.

I suspect you are supposed to find either "how many 'H's are there in the array of strings?" or "how many strings have an 'H' as the first letter?" - but either way you need to think a little more carefully before you jump into code. Remember, a dictionary cannot have duplicate Keys ...
 
Share this answer
 
Comments
Maciej Los 28-Jun-19 6:12am    
5ed!
BTW: i haven't seen your answer while posting mine.
OriginalGriff 28-Jun-19 6:20am    
That's OK - I hadn't seen yours while typing mine either! :laugh:
Maciej Los 28-Jun-19 6:31am    
:D
If i understand you well, you want to count repetition of chars in each string in string array...

So, you should define dictionary variable this way:
var map = new Dictionary<char, int>();

due to the Key should be a letter and Value should be the numer of repetition of Key.

C#
string[] inputArray = new string[] { "Hello1", "Hello2", "Hello3" };
Dictionary<char, int> map = new Dictionary<char, int>();
foreach (string s in inputArray)
{
    foreach(char c in s.ToArray())
		if(!map.ContainsKey(c))
			map.Add(c, 1);
		else
			map[c]= map[c]+1;
}

foreach (var mapitem in map.Keys)
{
    Console.WriteLine($"'{mapitem}' repeats {map[mapitem]} time(s)");
}


Result:
'H' repeats 3 time(s)
'e' repeats 3 time(s)
'l' repeats 6 time(s)
'o' repeats 3 time(s)
'1' repeats 1 time(s)
'2' repeats 1 time(s)
'3' repeats 1 time(s)
 
Share this answer
 
v2
Comments
OriginalGriff 28-Jun-19 6:20am    
Downvote countered - dunno which high-rep gave you that ...
CHill60 28-Jun-19 6:24am    
Not me! I also countered. Is that double-countering? :-)
Maciej Los 28-Jun-19 6:30am    
Well, it happens.
Thank you, Caroline.
OriginalGriff 28-Jun-19 6:38am    
I dunno. Who's countering? :laugh:
Maciej Los 28-Jun-19 6:30am    
Well, it happens...
Thank you, Paul.
Using Linq:
Dictionary<char, int> cntdic =
    string.Join("", this.inputArray)
        .GroupBy(c => c)
            .Select(c => new {name = c.Key, count = c.Count()})
                .ToDictionary(kvp => kvp.name, kvp => kvp.count);
 
Share this answer
 
v2
Comments
Maciej Los 30-Jun-19 6:15am    
Nice!
BillWoodruff[^] has inspired me to write a "full-linq-version" of solution with chars sorted by the count of repetition:

C#
string[] inputArray = new string[] { "Hello1", "Hello2", "Hello3" };
Dictionary<char, int> map = inputArray
	.SelectMany(word => word.ToArray())
	.GroupBy(c=>c)
	.OrderByDescending(grp=>grp.Count())
	.Select(grp=>new KeyValuePair<char, int>(grp.Key, grp.Count()))
	.ToDictionary(kvp=> kvp.Key, kvp=>kvp.Value);
 
Share this answer
 
v3
Comments
BillWoodruff 30-Jun-19 6:52am    
Now, considering I haven't voted for you or OG, the question becomes: should I vote you and OG down for not using Linq :)

Putting in an 'OrderBy ... a requirement the OP did not mention ... somehow makes my code not a "full Linq" solution ?

in fact, I deliberately avoided using 'Aggregate with strings because of the fact (string immutability) that it creates a bunch of strings that eat memory; there is a work-around for that using 'StringBuilder.

Whether 'SelectMany has any internal allocation: I don't know. It would be interesting to compare time and memory use of these methods, but, I bet we'd have to use giant data sets to tease out differences.

fyi ... no big deal ... I'd put the call to 'OrderBy in a different place to make only one call to 'Count() :)

var cntdic =
string.Join("", inputArray)

.GroupBy(c => c)

.Select(c => new {name = c.Key, count = c.Count()})

.OrderByDescending(grp => grp.count)

.ToDictionary(kvp => kvp.name, kvp => kvp.count);

cheers, Bill
Maciej Los 30-Jun-19 7:10am    
The question is not to voting down non-Linq solution, but to voting up good answers! :D
I've used double quotes with "full-linq-version" to interpret that statement with tongue in cheek.
As i said, i was inspired by you. I wanted to provide solution without using [string.Join()] method, but with [SelectMany()]. So, in this manner this is a "full-Linq-version" of solution.

Thanks for your interesting input, Bill.
BillWoodruff 30-Jun-19 7:18am    
"The question is not to voting down non-Linq solution, but to voting up good answers! :D"

I hope you noticed the smiley at the end of the first sentence :)

Do you have any specific knowledge about relative performance of string.Join vs. SelectMany ? That interests me.

Salvador Dali said: “It is not necessary for the public to know whether I am joking or whether I am serious, just as it is not necessary for me to know it myself.”

but, sadly, we are not Dali very often :(
Maciej Los 30-Jun-19 7:29am    
Oh, yeah. I've seen smiley at the end of first sentence.

No, i do not have knowledge about performance of string.Join vs. SelectMany.
BillWoodruff 2-Jul-19 6:01am    
another way you can improve your Linq code is to remove the unnecessary word => word.ToArray() : SelectMany will flatten the Array without calling 'ToArray:

inputArray.SelectMany(word => word)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900