using System using System Collections Generic public class NamesCount

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
public class NamesCount
{
private int count;
private Dictionary<string, int> counts = new Dictionary<string, int>();
/// <summary>
/// Adds the name.
/// </summary>
/// <param name="name">Name.</param>
public void AddName(string name)
{
int nameCount;
counts.TryGetValue(name, out nameCount);
if (nameCount == 0)
counts[name] = ++nameCount;
else counts[name]++;
count++;
}
/// <summary>
/// Returns proportion of parameter name in all calls to AddName.
/// </summary>
/// <returns>Double in interval [0, 1]. Returns 0 if AddName has not been called.</returns>
/// <param name="name">Name.</param>
public double NameProportion(string name)
{
return (double)counts[name] / count;
}
public static void Main(string[] args)
{
NamesCount namesCount = new NamesCount();
namesCount.AddName("James");
namesCount.AddName("John");
namesCount.AddName("Mary");
namesCount.AddName("Mary");
Console.WriteLine("Fraction of Johns: {0}", namesCount.NameProportion("John"));
Console.WriteLine("Fraction of Marys: {0}", namesCount.NameProportion("Mary"));
}
}