Click here to Skip to main content
15,894,740 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Write a program that creates a probabilistic model for a text file with counted occurrences of specific letters.
And it must display it in the table how many individual characters (in ASCII code) are in the text read from the file.
and the probability calculated using:
P = number of occurrences / all characters

What I have tried:

C#
var plik = File.ReadAllLines("example.txt");
        var liczba = 'z' - 'a' + 1;
        
        var liczniki = Enumerable.Repeat(0, liczba).ToList();
        
        foreach (var słowo in plik) {
            foreach (var znak in słowo) {
                
                if (znak >= 'a' && znak <= 'z') {
                    liczniki[znak - 'a'] += 1;
                }     
            }
Posted
Updated 27-Mar-20 1:09am
v2

The simplest solution is to read the whole file into a array of characters, then sort the array. That way, identical characters are next to each other and easy to count.

The second simplest way is to use Linq methods, and GroupBy the character. You can then you the Group Count to give you the numbers you need.

But the most efficient way is to have two arrays: one of the characters you are counting, and one of the counts. Preset the characters array to the actual characters, and preset the counts to all zero.
Then when you find a character, increment the count in the counts array. When you have processed the whole data, you can just print the results from the pair of arrays.
 
Share this answer
 
Comments
Maciej Los 27-Mar-20 7:08am    
5ed!
You can also use a Dictionary<char, int> which holds the current count for each character:
C#
Dictionary<char, int> dic = new Dictionary<char, int>();

foreach (char c in theString)
{
   if (!dic.ContainsKey(c)) { dic.Add(c, 0); }
   dic[c]++;
}
 
Share this answer
 
Comments
Maciej Los 27-Mar-20 7:08am    
5ed!

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