C# Unicode Count Frequency no dependencies
To do the lookup initialization correctly to match on int codes only add the function
public static IEnumerable<KeyValuePair<int, int>> ExpectedLookupCodes(string element, int total)
{
return element.ToCharArray().Select(componentChar => new KeyValuePair<int, int>((int)componentChar, total))
.ToList();
}
What happens is the looping element of Select
pulls down 2 int codes for the 🦥 so that when you put real input data in the original function typed to int code lookups for chars it will now match. Although it is confusing because 3 elements turns into 4 equivalent matches.
Complete code below
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static IEnumerable<KeyValuePair<int, int>> ExpectedLookupCodes(string element, int total)
{
return element.ToCharArray().Select(componentChar => new KeyValuePair<int, int>((int)componentChar, total))
.ToList();
}
public static Dictionary<int, int> CountFrequency(string input)
{
var results = new Dictionary<int, int>();
foreach (var element in input.ToCharArray())
{
var key = (int)element;
if (results.ContainsKey(key))
{
results[key] += 1;
continue;
}
results[key] = 1;
}
return results;
}
public static void Main()
{
var expected = new Dictionary<int, int>(
ExpectedLookupCodes("a", 3)
.Concat(ExpectedLookupCodes("b", 1))
.Concat(ExpectedLookupCodes("🦥", 1)));
var output = CountFrequency("aaab🦥");
var matches = expected.Count(expectedItem => expectedItem.Value == output[expectedItem.Key]);
Console.WriteLine($"Expected matches {expected.Keys.Count} actual matches {matches}");
}
}
Expected matches 4 actual matches 4