Skip to content

Instantly share code, notes, and snippets.

@haliphax
Created April 21, 2022 16:37
Show Gist options
  • Save haliphax/bdcb589bc459fd0623ee2d0d973b2549 to your computer and use it in GitHub Desktop.
Save haliphax/bdcb589bc459fd0623ee2d0d973b2549 to your computer and use it in GitHub Desktop.
Find longest common contiguous click stream between two user records
var user0 = new string[] { "/a", "/b", "/c", "/d", "/e", "/f" };
var user1 = new string[] { "/b", "/c", "/e", "/f" };
var user2 = new string[] { "/a", "/b", "/d", "/e", "/f" };
var user3 = new string[] { "/a", "/c", "/d", "/e", "/f" };
var user4 = new string[] { "/a", "/b", "/c", "/d", "/e", "/f" };
var user5 = new string[] { "/a", "/b", "/e", "/f" };
var user6 = new string[] { "/a", "/b", "/c", "/e", "/f" };
var user7 = new string[] { "/c", "/d", "/e", "/f" };
var user8 = new string[] { "/d", "/e", "/f" };
var user9 = new string[] { "/b", "/c", "/e", "/f" };
Dictionary<string, string> BuildDictionary(string[] clickStream)
{
var dict = new Dictionary<string, string>();
for (var i = 0; i < clickStream.Length; i++)
{
dict.Add(
clickStream[i],
(i == clickStream.Length - 1
? string.Empty
: clickStream[i + 1]));
}
return dict;
}
string[] LongestContiguousClickStream(string[] userA, string[] userB)
{
var dictA = BuildDictionary(userA);
var dictB = BuildDictionary(userB);
var shortest = (dictA.Count < dictB.Count ? dictA : dictB);
var longest = (dictA.Count >= dictB.Count ? dictA : dictB);
List<string>? longestCommon = null;
foreach (var url in shortest.Keys)
{
if (!longest.ContainsKey(url))
{
continue;
}
var contiguous = new List<string>();
var currentUrl = url;
var nextUrl = shortest[url];
while (true)
{
contiguous.Add(currentUrl);
if (nextUrl == string.Empty
|| longest[currentUrl] != nextUrl)
{
break;
}
currentUrl = nextUrl;
nextUrl = shortest[nextUrl];
}
if (contiguous.Count > (longestCommon?.Count ?? 0))
{
longestCommon = contiguous;
}
}
return longestCommon?.ToArray() ?? new string[] { };
}
var result = LongestContiguousClickStream(user3, user4);
Console.WriteLine(string.Join(", ", result));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment