using System.Collections.Generic;
public static void Main()
Console.WriteLine("\nThis program takes 2 user entries: int 'patternLength', string: 'input'.");
Console.WriteLine("'input' is then iterated over to find patterns of lengh 'patternLength'.");
Console.WriteLine("Recurring patterns are then output alongside their occurance count.");
Console.WriteLine("Assumptions:");
Console.WriteLine(" - 'patternLength' is an integer AND is less than 'input.Length'");
Console.WriteLine(" - 'input' is trimmed of leading and trailing whitespace, and escape characters are ignored.");
Console.WriteLine("\n==============================================================================================");
Console.Write("\nSearch for patterns of 'patternLength' (int): ");
string patternLengthString = Console.ReadLine();
bool parseSuccess = int.TryParse(patternLengthString, out patternLength);
Console.WriteLine("\nERR: '{0}' is not an integer.", patternLengthString);
Console.WriteLine("\nERR: patternLength {0} should be greater than zero.", patternLength);
Console.Write("\nWithin 'input' (string): ");
string input = Console.ReadLine();
formatOutput(match(input, patternLength));
private static Dictionary<string, int> match(string input, int patternLength)
Dictionary<string, int> results = new Dictionary<string, int>();
if (patternLength < input.Length)
for (int i = 0; i <= input.Length - patternLength; i++)
string pattern = input.Substring(i, patternLength);
if (results.ContainsKey(pattern))
catch (ArgumentException)
Console.WriteLine("\nERR: patternLength ({0}) in not shorter than input length ({1}) - no repeated patterns can be found.", patternLength, input.Length);
private static void formatOutput(Dictionary<string, int> results)
foreach (var result in results)
Console.WriteLine("\nThe following repeated patterns were found:\n");
Console.WriteLine("{0} : {1}", result.Key, result.Value.ToString().PadLeft(3));
Console.WriteLine("\nNo repeated patterns found.");