Last active
March 5, 2016 21:02
-
-
Save thdaraujo/e06093147134f61ea72a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Text.RegularExpressions; | |
using System.Threading.Tasks; | |
namespace MostFrequentSubstringApp | |
{ | |
/// <summary> | |
/// Find the Most Frequent Substring of length between k and l. | |
/// | |
/// Input: | |
/// n (string length) | |
/// k l | |
/// teststring | |
/// | |
/// Example (console): | |
/// 6 | |
/// 2 3 | |
/// ababab | |
/// | |
/// Result: ab | |
/// | |
/// </summary> | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var input = GetInputs(); | |
var k = ToInt(input.ElementAt(1).First()); | |
var l = ToInt(input.ElementAt(1).ElementAt(1)); | |
var s = input.ElementAt(2).First(); | |
var mostFrequentString = MostFrequentSubstring(s, k, l); | |
Console.Write("The most frequent substring is: "); | |
Console.WriteLine(mostFrequentString); | |
} | |
private static IList<IList<string>> GetInputs() | |
{ | |
return Enumerable.Range(0, 3) | |
.Select(x => GetLine()) | |
.ToList(); | |
} | |
public static int ToInt(string s) | |
{ | |
int aux = 0; | |
int.TryParse(s, out aux); | |
return aux; | |
} | |
public static IList<string> GetLine() | |
{ | |
Regex r = new Regex("\\s+", RegexOptions.Compiled); | |
var s = Console.ReadLine(); | |
return r.Split(s).ToList(); | |
} | |
public static string MostFrequentSubstring(string s, int k, int l) | |
{ | |
var sortedDict = new Dictionary<string, int>(); | |
while (k <= l) | |
{ | |
var substrings = Split(s, k); //divide into chunks | |
//add or increment | |
foreach (var item in substrings) | |
{ | |
if (sortedDict.ContainsKey(item)) | |
{ | |
sortedDict[item]++; | |
} | |
else{ | |
sortedDict.Add(item, 1); | |
} | |
} | |
k++; | |
} | |
var mostFrequent = sortedDict.OrderByDescending(w => w.Value).FirstOrDefault(); //a sorted dictionary would be better! | |
return mostFrequent.Key; | |
} | |
static IEnumerable<string> Split(string s, int size) | |
{ | |
return Enumerable.Range(0, s.Length / size) | |
.Select(i => s.Substring(i * size, size)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment