Skip to content

Instantly share code, notes, and snippets.

@junalmeida
Created June 5, 2020 15:13
Show Gist options
  • Save junalmeida/3d5c823566ed0d0d2eacc3584d1a9607 to your computer and use it in GitHub Desktop.
Save junalmeida/3d5c823566ed0d0d2eacc3584d1a9607 to your computer and use it in GitHub Desktop.
Get Longest Prefix from a set of strings with and without prefix sharing
// Enumerate all possible m-size combinations of [0, 1, ..., n-1] array
// in lexicographic order (first [0, 1, 2, ..., m-1]).
private static IEnumerable<int[]> GetCombinations(int m, int n)
{
int[] result = new int[m];
Stack<int> stack = new Stack<int>(m);
stack.Push(0);
while (stack.Count > 0)
{
int index = stack.Count - 1;
int value = stack.Pop();
while (value < n)
{
result[index++] = value++;
stack.Push(value);
if (index != m) continue;
yield return (int[])result.Clone(); // thanks to @xanatos
//yield return result;
break;
}
}
}
private static IEnumerable<T[]> GetCombinations<T>(T[] array, int m)
{
if (array.Length < m)
throw new ArgumentException("Array length can't be less than number of selected elements");
if (m < 1)
throw new ArgumentException("Number of selected elements can't be less than 1");
T[] result = new T[m];
foreach (int[] j in GetCombinations(m, array.Length))
{
for (int i = 0; i < m; i++)
{
result[i] = array[j[i]];
}
yield return result;
}
}
private static string LongestCommonPrefix(params string[] strs)
{
if (strs.Length == 0) return String.Empty;
Array.Sort(strs);
var first = strs[0];
var last = strs[strs.Length - 1];
var strbuilder = new StringBuilder();
for (int i = 0; i < first.Length; i++)
{
if (first[i] != last[i])
{
break;
}
strbuilder.Append(first[i]);
}
return strbuilder.ToString();
}
var occurences =
GetCombinations(arr, 2)
.Select(x => LongestCommonPrefix(x[0], x[1]))
.Where(x => !string.IsNullOrWhiteSpace(x))
.GroupBy(x => x)
.Select(x =>
{
var obj = new
{
Prefix = x.Key,
CountByCombinations = x.Count(),
Occurences = arr.Where(y => y.StartsWith(x.Key)).Count()
};
Console.WriteLine($"{obj.Prefix} (CountByCombinations: {obj.CountByCombinations}, Occurences: {obj.Occurences})");
return obj;
}).ToList();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment