Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created July 1, 2015 16:16
Show Gist options
  • Save VegaFromLyra/8282a0a03505116fe653 to your computer and use it in GitHub Desktop.
Save VegaFromLyra/8282a0a03505116fe653 to your computer and use it in GitHub Desktop.
Letter frequency
using System;
using System.Collections.Generic;
using System.IO;
namespace LetterFrequency
{
public class Program
{
public static void Main(string[] args)
{
using(StreamReader sr = new StreamReader("letter_frequencies.in"))
{
string num = sr.ReadLine();
int numberOfInputs = Int32.Parse(num);
string line;
int count = 1;
while ((line = sr.ReadLine()) != null &&
(count <= numberOfInputs)) {
var sortedTuples = generateSortedTuples(line);
using (StreamWriter sw = File.AppendText("letter_frequencies.out")) {
sw.WriteLine("Case #{0}", count);
foreach(var entry in sortedTuples) {
sw.WriteLine(String.Format("{0} {1}", entry.Ch, entry.Count));
}
}
count++;
}
}
Console.WriteLine("Done");
}
static List<Tuple> generateSortedTuples(string s) {
if (String.IsNullOrEmpty(s)) {
return new List<Tuple>();
}
s = s.Replace(" ", "");
var map = new Dictionary<char, int>();
foreach(var ch in s) {
if (map.ContainsKey(ch)) {
map[ch]++;
} else {
map.Add(ch, 1);
}
}
var allTuples = new List<Tuple>();
foreach(var key in map.Keys) {
allTuples.Add(new Tuple(key, map[key]));
}
allTuples.Sort();
return allTuples;
}
}
class Tuple : IComparable {
public Tuple(char ch, int count) {
Ch = ch;
Count = count;
}
public char Ch { get; private set; }
public int Count { get; private set; }
public int CompareTo(Object other) {
var otherTuple = other as Tuple;
int result = otherTuple.Count.CompareTo(Count);
if (result == 0) {
return Ch.CompareTo(otherTuple.Ch);
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment