Skip to content

Instantly share code, notes, and snippets.

@JamesKhoury
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesKhoury/3c61f0ddaf622b8b3c14 to your computer and use it in GitHub Desktop.
Save JamesKhoury/3c61f0ddaf622b8b3c14 to your computer and use it in GitHub Desktop.
Ayende.com Interview question: fix the index
public class Indexer
{
private Dictionary<string, List<string>> terms =
new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, List<List<string>>> docIDs =
new Dictionary<string, List<List<string>>>();
public void Index(string docId, string text)
{
List<List<string>> idList;
if(docIDs.TryGetValue(docId, out idList) == true)
{
foreach(List<string> ids in idList)
{
ids.Remove(docId);
}
}
idList = new List<List<string>>();
docIDs[docId] = idList;
var words = text.Split();
foreach (string term in words)
{
List<string> val;
if (terms.TryGetValue(term, out val) == false)
{
val = new List<string>();
terms[term] = val;
}
val.Add(docId);
idList.Add(val);
}
}
public List<string> Query(string term)
{
List<string> val;
terms.TryGetValue(term, out val);
return val ?? new List<string>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment