Skip to content

Instantly share code, notes, and snippets.

@dlidstrom
Created Apr 1, 2015
Embed
What would you like to do?
Output number of words occurring exactly n times
public class Program
{
static void Main()
{
var words = File.ReadAllText(@"C:\Programming\words.txt")
.Split(' ', '\r', '\n')
.Select(x => x.Trim())
.Where(x => !string.IsNullOrEmpty(x))
.ToArray();
var candidates = new Dictionary<string, int>();
var picked = new HashSet<string>();
var count = 9;
foreach (var word in words)
{
int currentSeenCount;
if (candidates.TryGetValue(word, out currentSeenCount) == false)
{
candidates.Add(word, 0);
}
candidates[word] = ++currentSeenCount;
if (currentSeenCount == count)
{
picked.Add(word);
}
else if (currentSeenCount > count)
{
picked.Remove(word);
}
}
Console.WriteLine("Found these words occurring {0} times:", count);
foreach (var x in picked)
{
Console.WriteLine(x);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment