-2

So I have a code here:

string word = "abba";
Counter(word);
public static List<Occur> Counter(string word)
{
    Occur Oc = new Occur();
    var ListNubmersOfWord = new List<Occur>();
    foreach (char c in word)
    {
        Oc.Letter = c;
        Oc.Number = word.Where(x => x == c).Count();
        ListNubmersOfWord.Add(Oc);
    }
    foreach(Occur item in ListNubmersOfWord)
    {
        Console.WriteLine(string.Join(" ", $"{item.Letter} {item.Number}"));
    }

    return ListNubmersOfWord;
}

Here is Occur Class:

public class Occur
{
    public int Number { get; set; }
    public char Letter { get; set; }
}

And the problem is that for some reason list "ListNubmersOfWord" only saves last letter and last occurrence. The outcome is :enter image description here Any ideas?

VaxiZ
  • 33
  • 1
  • 4

2 Answers2

2

In each iteration of the loop, you are setting Letter and Number to the same object reference. Try to instantiate new object inside the body of the foreach loop:

foreach (char c in word)
{
    Occur Oc = new Occur
    {
        Letter = c,
        Number = word.Where(x => x == c).Count()
    };
   
    ListNubmersOfWord.Add(Oc);
}
Joel Coehoorn
  • 380,066
  • 110
  • 546
  • 781
renzo
  • 106
  • 1
  • 7
0

Not only is the list of objects inefficient in your use case, but it would also cause repeated values in your example, you don't need char a,b in the list twice with the same count of occurrences. I would suggest using a Dictionary<char, int> and your method would be O(n) where n eqauls the number of characters in your string. You could also lookup the occurrence of a character in O(1) as well as get the count of a character in O(1):

string word = "abba";
Dictionary<char, int> charcount = Counter(word);

public static Dictionary<char, int> Counter(string word)
{
    Dictionary<char, int> charcount = new Dictionary<char, int>();
    
    foreach (char c in word)
    {
        if(charcount.ContainsKey(c))
           charcount[c]++;
        else
           charcount.Add(c, 1);
    }
    
    return charcount;
}
Ryan Wilson
  • 8,662
  • 1
  • 19
  • 34